Automate and Schedule Your Python Code Executions

Make your code work on your schedule

Rafael Cordeiro
Better Programming

--

Photo by Markus Spiske on Unsplash.

At this point, you have already written many lines of code, rewritten them, deleted some (or all) of them, and finally, after some tears and stress, you got it done!

It’s working perfectly, but you need to run this every day at 5 a.m. or once a week on Sundays. The responsibility of waking up just to click five buttons to start the execution or needing to stop in the middle of a meeting or task to initialize it is not the happiest moment of your day.

So, how can you easily automate it?

You just need three files (below) and Task Scheduler:

  • Your .py file.
  • A .sh that will call Python to you.
  • A .bat so we can schedule it.

A Quick Example

First file: test_PY_sh_bat.py

This code just opens a dialog box. There’s nothing important, but do you see the execute()? You only have to replace it with the function that you want to execute.

Note: Don’t forget that you need to have your main function in this file or import it from another file.

Second file: test_py_SH_bat.sh

export PATH="$PATH:/c/ProgramData/Anaconda3"
python test_PY_sh_bat.py |& tee ./logfiles/`date '+%Y_%m_%d'`_test_py_sh_bat.txt

This one is going to say, “Hey, I want to use the python.exe that is in this folder to run this script and save an execution log in this other folder with this name.” This way, you can know if everything is OK with your execution.

Third file: test_py_sh_BAT.bat

@echo on
cd "C:\Users\51028915\Documents\codes\scheduling_python_execution"
start test_py_SH_bat.sh
exit

The .bat will be used as a caller, so just say where it is and what it has to do (in this case, start the process).

Scheduling the Execution

Open Task Scheduler:

Click “Task Scheduler Library”:

Select “Create Basic Task”:

Enter a name and a description for the task:

Select the execution frequency in the “Trigger” section:

Choose a time and date for the execution of the task:

In the “Action” section, choose the “Start a program” option:

Browse the .bat file:

Click “Finish”:

And that’s it! From now on, you don’t need to manually run your code!

I hope this article has helped you. You can download the example files on GitHub.

--

--