Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a cronjob with a python virtual environment?

Usually I SSH into my EC2 instance and run:

source MYVENV/bin/activate

How do I set my cronjob to activate the virtual environment? My Django script requires ENVIRONMENT variables that are stores in ~/.bash_profile

I tried following the steps here to no avail

Cron and virtualenv

SHELL=/bin/bash
*/1 * * * * root source /home/ec2-user/MYVENV/activate && python /home/script.py

This is my current setup above.

I get this following error in the log:

/bin/bash: root: command not found

like image 887
superdee Avatar asked Apr 26 '19 02:04

superdee


2 Answers

create a shell script eg scripts.sh

#!/bin/bash
source /home/user/MYVENV/bin/activate
python /path/to/file/script.py

Then in cron put

*/1 * * * * bash /path/to/shell/script/scripts.sh

The script will load all your environment variables and execute from the python in your environment

like image 156
Piakkaa Avatar answered Oct 14 '22 18:10

Piakkaa


you can just run the python interpretor from your environment directly eg

MYENV/bin/python script.py

to find out what is the directory to your environment python interpretor, change into the virtual env then run

which python

in your case, this should become

*/1 * * * * /home/ec2-user/MYVENV/python /home/script.py
like image 29
Nic Wanavit Avatar answered Oct 14 '22 18:10

Nic Wanavit