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

Scheduling django command within virtual env with cron

我正在尝试使用 cron 安排在 virtualenv 中执行的 django 命令的执行。我正在安排脚本的执行,我在其中激活 thye 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 作业:

* * * * * 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

我们将不胜感激。

我通过从脚本中删除 virtualenv 激活解决了这个问题:

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