Python:如何设置crontab的virtualenv? [英] Python: how to set virtualenv for a crontab?
问题描述
我想设置一个crontab来运行一个Python脚本。
说脚本是这样的:
#!/ usr / bin / python
printhello world
有没有办法我可以指定一个virtualenv的Python脚本运行?在shell中我只需要:
〜$ workon myenv
$
解决方案有什么办法可以在crontab中激活virtualenv吗? >如果你使用workon,你实际上是使用virtualenv包装器,这是另一层抽象,位于virtualenv的顶部。 virtualenv可以通过cd到您的virtualenv根目录并运行来激活:
source bin / activate
workon是由virtualenv包装器提供的命令,而不是virtualenv,它做一些额外的东西, 。你真正需要做的是将virtualenv根目录中的bin / activate文件源为激活一个virtualenv。
你可以设置你的crontab来调用bash脚本这样做:
#! / bin / bash
cd my / virtual / env / root / dir
source bin / activate
#virtualenv现在处于活动状态,这意味着您的PATH已被修改。
#不要尝试从/ usr / bin / python运行python,只需运行python和
#让PATH确定运行哪个版本(基于你的
# virtualenv已配置)。
python myScript.py
I want to set up a crontab to run a Python script.
Say the script is something like:
#!/usr/bin/python print "hello world"
Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do:
~$ workon myenv
Is there something equivalent I could do in crontab to activate a virtualenv?
解决方案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
这篇关于Python:如何设置crontab的virtualenv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!