When you have a python virtual environment you would activate the virtual environment’s python as such:
But when you try to run this command in cron it will not work because by default crontab uses /bin/sh which does not support the source command.
So you can do the following in your crontab:
SHELL=/bin/bash */59 * * * * source /home/sven/python_test_envs/test_env/bin/activate && /home/sven/python_test_envs/test_env/bin/python3 /home/sven/dev_stuff/python_dev/grafana_grab.py && deactivate >> /tmp/cronout.txt 2>&1
Bascially just put this command as your first line in your crontab and this tells crontab to use /bin/bash
This part “&& deactivate >> /tmp/cronout.txt 2>&1” tells cron to output data to this location so we can see if it encounters any errors.
In Ubuntu 22 however, you can do “grep CRON /var/log/syslog” to see what cron is doing.
Another solution can be found here should you no be able to use /bin/bash:
Essentially what it says is to do this:
cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py
Here you just CD to your virtual environment and use that Python to run your python script without activating the virtual environment.