我正在尝试从cron运行Django管理命令。我使用virtualenv保持我的项目沙盒。
我在这里和其他地方看到了从virtualenv中运行管理命令的示例,例如:
0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command arg
然而,尽管syslog显示了任务应该在何时启动的条目,但该任务从未实际运行(脚本的日志文件为空)。如果我从shell中手动运行这一行,它将按预期工作。
我目前可以通过cron运行命令的唯一方法是将命令分解并将它们放在一个哑bash包装脚本中:
#!/bin/sh
source /home/user/project/env/bin/activate
cd /home/user/project/
./manage.py command arg
编辑:
Ars提出了一个命令的工作组合:
0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg
至少在我的例子中,调用virtualenv的激活脚本没有任何作用。这招管用,所以节目继续。
我已经在我的Django项目中添加了下面的脚本manage.sh,它获取了virtualenv,然后运行manage.py脚本,不管你传递给它什么参数。它使得在virtualenv (cron, systemd单元,基本上任何地方)中运行命令变得非常容易:
#! /bin/bash
# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)
# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate
# run manage.py script
$DIR/manage.py "$@"
然后在你的cron条目中运行:
0 3 * * * /home/user/project/manage.sh command arg
只需记住,您需要使manage.sh脚本可执行
我已经在我的Django项目中添加了下面的脚本manage.sh,它获取了virtualenv,然后运行manage.py脚本,不管你传递给它什么参数。它使得在virtualenv (cron, systemd单元,基本上任何地方)中运行命令变得非常容易:
#! /bin/bash
# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)
# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate
# run manage.py script
$DIR/manage.py "$@"
然后在你的cron条目中运行:
0 3 * * * /home/user/project/manage.sh command arg
只需记住,您需要使manage.sh脚本可执行
你应该能够通过在虚拟环境中使用python来做到这一点:
/home/my/virtual/bin/python /home/my/project/manage.py command arg
编辑:如果你的django项目不在PYTHONPATH目录下,那么你需要切换到正确的目录:
cd /home/my/project && /home/my/virtual/bin/python ...
您也可以尝试从cron记录失败:
cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1
另一件要尝试的事情是在你的manage.py脚本最上面做同样的改变:
#!/home/my/virtual/bin/python