views:

85

answers:

1

I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed.

I have seen examples here and elsewhere that show running management commands from within virtualenv's like:

0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command arg

However, even though syslog shows an entry when the task should have started, this task never actually runs (the log file for the script is empty). If I run the line manually from the shell, it works as expected.

The only way I can currently get the command to run via cron, is to break the commands up and put them in a dumb bash wrapper script:

#!/bin/sh
source /home/user/project/env/bin/activate
cd /home/user/project/
./manage.py command arg

Please enlighten me what the difference is. What am I missing?

Thanks

EDIT:

ars came up with a working combination of commands:

0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg

At least in my case, invoking the activate script for the virtualenv did nothing. This works, so on with the show.

+4  A: 

You should be able to this by using the python in your virtual environment:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory:

cd /home/my/project && /home/my/virtual/bin/python ...

You can also try to log the failure from cron:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

Another thing to try is to make the same change in your manage.py script at the very top:

#!/home/my/virtual/bin/python
ars
That also does not work. Forgot to put that in my list of things that do not work. Yes, I can run that command manually in the shell but it does not work from cron.
John-Scott
Did you replace `~` with the full path? (You probably did, just making sure ...)
ars
Ah, you've come up with a working example!I've tried about every combination and activating the virtualenv appears to have no effect whatsoever. I do set my PYTHONPATH in .bashrc but this apparently is not used by cron? Will update my question to highlight your answer.
John-Scott
Yeah, I'd forgotten that cron runs under a very minimal environment. The general recommendation is to write bash scripts to set up whatever environment your job will need. You could try sourcing the bash profile directly in cron, but this can lead to subtle bugs depending on what's in your profile (perhaps if you have a separate and minimal profile for such needs, it would be fine).
ars