使用cron在虚拟环境中调度django命令

时间:2015-01-09 09:50:57

标签: django cron virtualenv

我试图安排用cron执行django命令,在virtualenv中执行。我安排了脚本的执行,我激活了你的virtualenv,然后执行命令。

问题在于,当试图激活virtualenv时,它会引发错误没有这样的文件或目录

/opt/django/myproj/myapp/cron/myscript.sh: line 2: /opt/virtualenvs/myvirtualenv
/bin/activate
: No such file or directory
Traceback (most recent call last):
  File "/opt/django/myproj/manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 261, in fetch_command
    commands = get_commands()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 107, in get_commands
    apps = settings.INSTALLED_APPS
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 132, in __init__
    % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'myproj.settings

' (Is it on sys.path? Is there an import error in the settings file?): No module named settings

这就是我所拥有的:

CRON JOB:

* * * * * bash /opt/django/myproj/myapp/cron/myscript.sh > /opt/django/myproj/log/myscript.log 2>&1

MYSCRIPT.SH(简化)

1 #!/bin/bash
2 source /opt/virtualenvs/myvirtualenv/bin/activate
3 python /opt/django/myproj/manage.py testcommand 

MYSCRIPT.SH(原始剧本,无论如何都是相同的结果)

1 #!/bin/bash
2 SHELL=/bin/bash
3 DJANGO_SETTINGS_MODULE=myproj.settings
4 VIRTUALENV_DIR='/opt/virtualenvs/myvirtualenv'
5 export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
6 export PYTHONPATH=${VIRTUALENV_DIR}:${PYTHONPATH}
7 source ${VIRTUALENV_DIR}/bin/activate
8 python /opt/django/myproj/manage.py testcommand

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

我通过从脚本中删除virtualenv激活来解决它:

#!/bin/sh
/opt/virtualenvs/myvirtualenv/bin/python /opt/django/myproj/manage.py testcommand