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

前端 未结 3 546
灰色年华
灰色年华 2020-12-21 03:30

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 sc

相关标签:
3条回答
  • 2020-12-21 04:06

    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
    
    0 讨论(0)
  • 2020-12-21 04:11

    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
    
    0 讨论(0)
  • 2020-12-21 04:20

    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

    0 讨论(0)
提交回复
热议问题