I have the following goal: I have a python script, which should be running in my custom Anaconda environment. And this process needs to be automatizated.
The first thing I've tried was to create an .exe file of my script using pyinstaller in the Anaconda command prompt, opened in my environment. And put the .exe into Windows Task Scheduler. But I did not succeeded cause my script seems to be too complex, contain too many imports so pyinstaller didn't create the .exe.
The next thing I thought of was an attempt to run my script using Windows CMD with appropriate attributes, and also put it into Windows Task Scheduler.
Now my question is if there is a way to set up Task Scheduler so it could run CMD with attributes, which would activate my environment and with this environment run my script right away? I need this to be done automatically once a day at a given time.
Update 3: am I blind or what?
I mean, here it is:
You could
- Create a
.bat
file (e.g. run_python_script.bat
) with contents shown below.
- Create task in "Task Scheduler" to run the
.bat
file.
1.a. The .bat file contents with conda environments
- Check your
<condapath>
. Your conda.exe
is located at <condapath>/Scripts
.
- Put into your .bat file
call "<condapath>\Scripts\activate.bat" <env_name> & cd "<folder_for_your_py_script>" & python <scriptname.py> [<arguments>]
<env_name>
is the name of the conda environment.
<folder_for_your_py_script>
is the folder that contains <scriptname.py>
<scriptname.py>
is the script you want to start.
[<arguments>]
represent the optional arguments (if you need to give arguments to your script)
1.b. The .bat file contents with venv
"<path_to_python_exe>" "<path_to_python_script>" [<arguments>]
where
<path_to_python_exe>
is the path to your python executable. If you are using a virtual environment (venv
), then use the python.exe
found in the /venv/Scripts
folder
<path_to_python_script>
is the path to your python script.
[<arguments>]
represent the optional arguments (if you need to give arguments to your script)
2. Creating task in Task Scheduler
- Go to "Task Scheduler" -> "Create Basic Task"
- Give the name & timing info
- Add to the "Program/Script" the path to your
run_python_script.bat
.
Appendix: Creating venv
with Anaconda
It seems that conda create
command does not create similar virtual environments as python -m venv
command. To create normal python virtual environment with the venv
- Check your
<condapath>
. Your conda.exe
is located at <condapath>/Scripts
.
- Create virtual environment to folder you want (let's call it
venv_folder
), by running following command in <venv_folder>
<condapath>\python.exe -m venv venv
- Now, your
<path_to_python_exe>
will be <venv_folder>\venv\Scripts.python.exe
.
- If you need to install packages to this virtual environment, you use
<venv_folder>\venv\Scripts.python.exe -m pip install <package_name>