Search code examples
python-3.xbatch-filestartuppython-venvpythonw

How to open a python file in background with a virtual environment activated on PC startup?


I have a python file that needs a virtual environment to be activated in order to be run, and I want this file to be run whenever I start my PC. Problem is a terminal window opens even though I'm using pythonw. It is just a blank terminal window.

So here is what I did, I created a bat file that looks like this d:\folder\venv\Scripts\pythonw.exe d:\folder\thefile.py this does not fully work because even though it does not open a terminal window for the python file it does open a blank terminal window that I have to close manually. I want to get rid of this. Finally I thought I can put the bat file here C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup


Solution

  • I faced this issue, and I put a Python script in shell:startup with .pyw but it still opened a terminal. here are the essential tips:

    1. Ensure that pythonw.exe was used as your interpreter.
    2. start your bat file with @echo off your bat file should be like this:
    @echo off
    start /B pythonw.exe path_to_your_script.py
    exit
    

    This command will automatically open a blank terminal and close it within a second.

    another way is instead of directly placing the .pyw file in the startup folder, you can create a shortcut to the script:

    • Navigate to your script.
    • Right-click and choose "Create shortcut".
    • Place this shortcut in your startup folder.