[Answer]-Django: Cron job is not executing python script

1👍

Step 1: Add Shebang to script

Unix scripts use a line called “Shebang

So your first line should look like this:

#!/usr/bin/env python

Stept 2: Make script executable

  1. Go to the folder with your script mysript.py
  2. Execute chmod +x myscript.py in console.
  3. Verify that it is executable by executing it with ./myscript.py.

Step 3: Add it to CRON

  1. Type crontab -e in terminal.
  2. Add a line like this:

    30 13 * * * /home/yourusername/myscript.py

  3. Verify with crontab -l that everything worked.

(see cyberciti.biz for more information)

Debugging python scripts

import datetime
import getpass

now = datetime.datetime.now()

# Open file to append
with open("/home/user/myscript.log", "a") as f:
    f.write("Script started at %i.%i.%i (%i:%i:%i) by %s" % (now.day, now.month, now.year, now.hour, now.minute, now.second, getpass.getuser()))

[...]
with open("/home/user/myscript.log", "a") as f:
    f.write("File 'xy' was opened.")

0👍

check first your crontab is running. add a job to create a file in tmp folder. IF it is running. try to give full path for python like

* /usr/bin/python /home/path of your django project/manage.py …

👤loki

0👍

In your terminal write crotab -e . There put your

* * * * * /usr/bin/python /Users/path_to_csv/test_subprocess.py

And in the test_subprocess.py add

DJANGO_SETTINGS_MODULE=project.settings

and also note that DJANGO_SETTINGS_MODULE=project.settings will only work if you run this cron job in project folder. So it would be better to use it as DJANGO_SETTINGS_MODULE=/pathToProject/project.settings

0👍

!/usr/bin/env python is fine

just set project setting full path to DJANGO_SETTINGS_MODULE

DJANGO_SETTINGS_MODULE=/Users/path_to_project/project.settings

          • python /Users/path_to_csv/test_subprocess.py

Leave a comment