Emm
Emm

Reputation: 2507

Cannot schedule a python script to run through Windows Task Scheduler

I have set up my windows task scheduler to create a task to run a python script that will send out an email to a few people (including myself).

I added the location the location of my Python in the actions tab in Program/script

C:\Users\User\AppData\Local\Programs\Python\Python37\python.exe

I added my python file as an argument and the path to the file as Start in:

C:\Users\User\Documents\GitHub\automation

However when I run the script (I am testing it by running it every 5 minutes for 15 minutes). Python.exe opens up briefly but the emails in my python script are not sent, which means the script isn't running. I have tested my code several times and know that it works.

Upvotes: 0

Views: 4608

Answers (2)

Krumelur
Krumelur

Reputation: 32597

Most likely the task scheduler runs under a service account in Windows. This means it won’t have access to all the packages you installed locally. To remedy this, try

pip freeze —user > requirements.txt

Then in an admin command window:

pip install requirements.txt

This will reinstall packages so that they are available for all users

Upvotes: 2

Stephen
Stephen

Reputation: 1528

If you check the history for that task in your task scheduler, you'll see the exit code returned by the python interpreter. Most likely, this is either a permission issue (the user account you've configured the interpreter to run as does not have sufficient privileges to execute all the statements contained in the script) or a missing requirement. You mentioned in the comments that you were using an IDE; if that's the case, then you're likely using a virtual environment in your IDE and therefore the system installation of python is missing the package that you were using to run the code, leading to the emails not being sent out.

You can resolve any dependency errors by making sure to run pip install -r <requirements.txt file location> if you have a requirements.txt file specified in your IDE project, or you can simply manually install the required packages with similar pip commands. If the issue is Windows permissions, you can create a new Windows user with higher permissions (given that you have admin access on your own system) and have the task run as that user, or you can enable the Run with highest privileges check-button property in your task.

Upvotes: 1

Related Questions