I'm not sure about workon
, but it's pretty straightforward for venv
. The only thing to remember is that crontab
uses sh
by default, not bash
, so you need to use the .
command instead of source
.
Here are examples if you have a file ~/myproject/main.py
:
* * * * * cd ~/myproject && . .venv/bin/activate && python main.py > /tmp/out1 2>&1
You could also directly call the specific path of the python
in the venv directory, then you don't need to call activate
.
* * * * * ~/myproject/.venv/bin/python ~/myproject/main.py > /tmp/out2 2>&1
The downside of that is you would need to specify the project path twice, which makes maintenance trickier. To avoid that, you could use a shell variable so you only specify the project path once:
* * * * * project_dir=~/myproject ; $project_dir/.venv/bin/python $project_dir/main.py > /tmp/out3 2>&1