0

I'm trying to run a Python script which needs to be executed with virtualenv activated with cron

Based on this Cron and virtualenv thread I've come up with this:

SHELL=/bin/bash
0 * * * * export FLASK_APP=/home/mark/off_web/project/__init__.py
1 * * * * export FLASK_ENV=development
*/10 * * * * root source /home/mark/off_web/venv/bin/activate && /usr/bin/python3 /home/mark/web_off/deletion.py

After editing I can see output crontab: installing new crontab but then I take a look if the script has been executed and can see that it hasn't. Does crontab: installing new crontab also mean that it's triggering new execution ? * * * * means that it will be ran every day.

Edit:

edited crontab to look like:

0 * * * * /home/mark/off_web/kick_off_deletion_script.sh

kick_off_deletion_script:

#!/bin/sh

export FLASK_APP=/home/mark/off_web/project/__init__.py
export FLASK_ENV=development
. /home/mark/off_web/venv/bin/activate
/usr/bin/python3 deletion.py
echo "Executed"

after running the shell script I get ModuleNotFoundError: No module named 'flask' despite it being installed.

itsallgood
  • 75
  • 9
  • 1
    Why not just make a shell script that will export your variables, activate your enviroment and call the python script, that way you just need one entyr on the cron to call the shell script – Chris Doyle Apr 28 '21 at 18:38
  • Yeah, I can definitely do that. In fact I've done it already. For some reason it throws an error saying Flask isn't installed even though it is. I'll add edit. – itsallgood Apr 28 '21 at 19:01
  • 2
    It's cause you execute the default python `/usr/bin/python3 deletion.py`. Change it to `python3 deletion.py` and you should be good – information_interchange Apr 28 '21 at 19:05
  • when you activate enviroment then use `which python3` to get path to python used in this enviroment - it should be something like `/home/mark/off_web/venv/bin/python3` - and you may try to use this path to run code without starting enviroment - so you may try to use it in cron. – furas Apr 28 '21 at 20:14
  • `crontab: installing new crontab` means that it restarted `cron` with your new settings. – furas Apr 28 '21 at 20:19
  • `* * * *` means that it will be ran every minut in every day. it gives 1440 runs every day (24h * 60min). Web service usually starts only once to run it all time. For example you could use `@reboot` in cron to start it when you start computer. On some Linux other method is to use service [supervisord](http://supervisord.org/) which will check if your program is running and it will automatically restart it when it is crashed. Maybe you find more in [Full Stack Python](https://www.fullstackpython.com/) – furas Apr 28 '21 at 20:24

0 Answers0