Run a python script in virtual environment from windows task scheduler

Create batch file with these commands:

c:\__full_path_to_virtualenv__\Scripts\activate.bat && python __full_path_to_python_script__.py

&& means run command2 if command1 completed successfully.

Then set that batch file as script to run. You don't need to set any additional arguments in task scheduler (or you can set them in batch file anyway) and can set Start in if script has to read/write from specific directory and uses relative paths.


Though the answer by mx0 above seems to work, I have set up Task Scheduler to run a flask web app on bootup. In this case, manual starting works fine, but manual ending does not. Ending the task kills the cmd.exe task that sets up the virtual environment, but the python.exe continues to run.

The solution that I found worked was from this reddit post which skips the virtual environment activation to call the python executable directly:

path\to\venv\Scripts\python.exe path\to\script.py

I'm not sure how robust this will be, but at least this way ending the task will end the python.exe