6

I have a crontab file supposedly executing a Django command after loading the project virtual environment:

*/1 * * * * source /home/virtualenvs/mydjangoproject-venv/bin/activate && python /home/www/production/mydjangoproject/manage.py mydjangocommand

...but it does absolutely nothing. The cron log outputs no particular problem:

Mar 13 19:51:01 110 CRON[23807]: (root) CMD (source /home/virtualenvs/mydjangoproject-venv/bin/activate && python /home/www/production/mydjangoproject/manage.py mydjangocommand)

Needless to say, the command itself works perfectly when copy-pasted in the shell.

I know it is related to the environment variables of my crontab, but I'm very uneducated regarding this matter, and I have no idea what to do especially when it is run under a python virtual env. Should it use my user environment variables? The ones from the virtualenv? How to implement that? Thanks!

NB: In case it helps, I have the following output of my crontab environment variables (when exporting "env" to a file through the crontab):

HOME=/root
LOGNAME=root
PATH=/usr/bin:/bin
LANG=en_US.UTF-8
SHELL=/bin/sh
LC_ALL=en_US.UTF-8
PWD=/root

And the following environment variables under the project virtual environment:

TERM=xterm-256color
SHELL=/bin/bash
SSH_CLIENT=x.x.x.x 53007 22
OLDPWD=/root/production/mydjangoproject
SSH_TTY=/dev/pts/0
LC_ALL=en_US.UTF-8
USER=root
VIRTUAL_ENV=/home/virtualenvs/mydjangoproject-venv
MAIL=/var/mail/root
PATH=/home/virtualenvs/mydjangoproject-
venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/root
LANG=en_US.UTF-8
PS1=(mydjangoproject-venv)${debian_chroot:+($debian_chroot)}\u@$(hostname -f):\w\$ 
SHLVL=1
HOME=/root
LS_OPTIONS=--color=auto --group-directories-first
LOGNAME=root
SSH_CONNECTION=x.x.x.x 53007 x.x.x.x 22
LC_CTYPE=en_US.UT
7

There are a couple of ways to solve this:

First, it doesn't work because /bin/sh is the shell cron uses to run commands, but /bin/sh doesn't support source. So the quick fix is to set SHELL=/bin/bash in the crontab.

Or...

Second, it's not necessary to source virtualenv/bin/activate anyway. You can just call the virtualenv python directly.

* * * * * cd /home/www/production/mydjangoproject; /home/virtualenvs/mydjangoproject-venv/bin/python manage.py mydjangocommand

These were taken from this question on SO, the answers to which may contain other ideas for people in similar but not quite the same circumstances.

  • Thanks a lot, I have tried both your solutions, and both work! So it wasn't a problem exactly related to environment variables. – bolino Mar 14 '18 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.