Run a Python script via Cron using virtual environments

Run a Python script via Cron using virtual environments

Virtual environments in Python are very useful. They allow you to isolate libraries, and thus restrict a specific version of a library to a particular script. Furthermore, it's common practice to create an environment when developing scripts, or when testing to validate proper functionality after updating libraries without breaking production.

However, to activate these environments, it is necessary to activate them manually with a command, except that with the execution of Cron, it completely ignores this step, even if it is specified in the command line.

To resolve the issue, you need to run the Python binaries located in the environment folder. This ensures that the correct libraries with the correct versions are loaded.

In our example, the script and the virtual environment are located in the /home/localadmin/project folder. The folder containing the environment is called venv.

Therefore, if we want to run a script every 4 hours each day, the line would be as follows:

00      */4     *       *       *       /home/localadmin/project/venv/bin/python /home/localadmin/project/main.py
You must always provide the absolute (full) path for this to work.

Naturally, the path needs to be adapted to your configuration and locations, bearing in mind that the environment folder may not be in the same place as the project.