How to set virtualenv for a crontab?

喜欢而已 提交于 2019-11-28 15:25:07
Andy White

If you're using "workon" you're actually using "virtualenv wrapper" which is another layer of abstraction that sits on top of virtualenv. virtualenv alone can be activated by cd'ing to your virtualenv root directory and running:

source bin/activate

workon is a command provided by virtualenv wrapper, not virtualenv, and it does some additional stuff that is not necessarily required for plain virtualenv. All you really need to do is source the bin/activate file in your virtualenv root directory to "activate" a virtualenv.

You can setup your crontab to invoke a bash script which does this:

#! /bin/bash    
cd my/virtual/env/root/dir
source bin/activate

# virtualenv is now active, which means your PATH has been modified.
# Don't try to run python from /usr/bin/python, just run "python" and
# let the PATH figure out which version to run (based on what your
# virtualenv has configured).

python myScript.py

Another solution that works well for me...

0    9    *    *    *    /path/to/virtenv/bin/python /path/to/cron_script.py

I prefer using python directly from the virtualenv...

With bash, you can create a generic virtual env wrapper that you can use to invoke any command, much like how time can wrapper any command.

virt_env_wrapper.bash:

#!/bin/bash    
source path/to/virtual/env/bin/activate
"$@"

Bash's magical incantation "$@" re-escapes all tokens on the original command line so that if you were to invoke:

virt_env_wrapper.bash python foo.py bar 'baz blap'

foo.py would see a sys.argv of ['bar', 'baz blap']

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!