在crontab中运行django独立脚本会破坏与django相关的任何导入命令

时间:2013-07-22 17:07:48

标签: python django crontab

我已经尝试了很多解决方案来解决这个问题,包括使用django的自定义管理命令,带路径配置的python脚本以及设置DJANGO_ENV_VAR等等。当我尝试从django导入某些内容时,一切都会中断,例如:

from django.db

import django.utils

以下是我的一个错误追溯的示例:

Traceback (most recent call last): 
File "/home/username/webapps/folder/Project/scripts/standalone.py", line 29, in 
<module> from Model.models import Model File "/home/username/webapps/folder/
Project/App/models.py", line 15, in <module> from django.db import models
ImportError: No module named django.db

在crontab中,我遵循了所有一般程序。所有时间配置都是正确的,所有脚本都以其完整路径调用,即。 /usr/bin/python2.7或/ usr / bin / sh。

当任何这些脚本在shell中而不是在crontab中运行时,它可以正常工作: 喜欢:

python2.7 manage.py killModels

sh scrapper.sh >> log.log

这是crontab:

8,38,58 * * * * ~/webapps/Folder/apache2/bin/start
#*/1 * * * * /bin/sh ~/webapps/Folder/Project/scripts/unpack.sh >> ~/webapps/Folder/Project/logs/unpack.log 2>&1
*/25 * * * * ~/bin/indexer Model_Model --rotate --config    
~/webapps/Folder/Project/misc/sphinx/sphinx.conf >> ~/webapps/Folder/Project/logs/searchd_log.txt
*/25 * * * * /bin/sh ~/webapps/Folder/Project/scripts/check_sphinx.sh >> ~/webapps/Folder/Project/logs/searchd_log.txt
0 2 * * * mysqldump --defaults-file=~/db_backups/Project_db.cnf -u Project_db Project_db >  ~/db_backups/Project_db-`date +\%Y\%m\%d`.sql 2>> ~/db_backups/cron.log
*/1 * * * * /usr/local/bin/python2.7 ~/webapps/Folder/Project/manage.py UpdateModels >> ~/webapps/Folder/Project/logs/unpack.log 2>&1

有人有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

替换:

*/1 * * * * /usr/local/bin/python2.7 \
            ~/webapps/Folder/Project/manage.py UpdateModels \
            >> ~/webapps/Folder/Project/logs/unpack.log 2>&1

由:

*/1 * * * * (cd ~/webapps/Folder/Project/; \
             /usr/local/bin/python2.7 manage.py UpdateModels) \
             >> ~/webapps/Folder/Project/logs/unpack.log 2>&1

通过此更改,manage.py可以找到django应用程序。