pythonbatch-filecmdvirtualenv

Activate virtualenv and run .py script from .bat


I'd like to use Windows Task Scheduler to run a python script within a virtual environment. I'd like the Scheduler to run a .bat file that will

  1. activate the virtualenv
  2. run the script

These steps work together from the command line, and they work individually in a .bat, but I can't seem to get them to work together from the .bat. It seems the virtualenv is not fully activated when I try to execute the python script and confused as to why.

My .bat looks like this:

call workon venv
cd path/to/Python/proj
python -m script.py

I've tried adding timeouts immediately after the call to workon and tried moving the workon to seperate .bat called from my first file, but the other lines still execute before the virtualenv is activated. Any help is greatly appreciated!


Solution

  • You can use an ampersand & operator in a oneliner batch file.

    call workon venv & cd path/to/Python/proj & python -m script.py
    

    It will run each command after the other.

    You can also double up the ampersand to make it a conditional operator. &&:

    call workon venv && cd path/to/Python/proj && python -m script.py
    

    Here the command will only run, if the previous command completed successfully, in other words ERRORLEVEL = 0