11

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

superdee
  • 637
  • 10
  • 23
  • https://stackoverflow.com/a/54193147/7976758 In your case something unusual is in `~/.bash_profile` so source it before running the script. – phd Apr 26 '19 at 06:07
  • https://stackoverflow.com/search?q=%5Bcron%5D+%5Bvirtualenv%5D+variables – phd Apr 26 '19 at 06:07

3 Answers3

17

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

Piakkaa
  • 740
  • 6
  • 12
7

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
Nic Wanavit
  • 2,363
  • 5
  • 19
  • 31
2

you can create a single wrapper bash script for executing your Django script. See the example below.

#!/bin/bash -l       // this should pick up your ~/.bash_profile environment variables

cd /path to project dir/   // set it up if your project is not in python path

source /Users/<user>/.virtualenvs/dslab/bin/activate // this activates your environment 

python /home/script.py   // run your script
himanshu219
  • 654
  • 7
  • 22