如何为 crontab 设置 virtualenv? [英] How to set virtualenv for a crontab?

查看:38
本文介绍了如何为 crontab 设置 virtualenv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个 crontab 来运行 Python 脚本.

I want to set up a crontab to run a Python script.

说脚本是这样的:

#!/usr/bin/python
print "hello world"

有没有办法可以为该 Python 脚本指定一个 virtualenv 来运行?在 shell 中,我会这样做:

Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do:

~$ workon myenv

我可以在 crontab 中做一些等效的事情来激活 virtualenv 吗?

Is there something equivalent I could do in crontab to activate a virtualenv?

推荐答案

如果您使用workon",您实际上是在使用virtualenv wrapper",它是位于 virtualenv 之上的另一层抽象.virtualenv 可以通过 cd 到您的 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 是由 virtualenv 包装器提供的命令,而不是 virtualenv,它执行一些普通 virtualenv 不一定需要的额外内容.你真正需要做的就是在你的 virtualenv 根目录中找到 bin/activate 文件来激活"一个 virtualenv.

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.

您可以设置您的 crontab 来调用执行此操作的 bash 脚本:

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

这篇关于如何为 crontab 设置 virtualenv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆