Django: Cron job is not executing python script
Question: I am using csvimporter to import some a csv file into a Django model. I have 2
scripts - one python script to take the file:

    
    
    import subprocess
    
    subprocess.call("python manage.py csvimport --model='csv_reader.csv' /Users/path_to_csv", shell = True)
    

And a django script to delete objects from the model:

    
    
    from csv_reader.models import *
    
    csv.objects.all().delete()
    

Both of the scripts work fine when ran manually from the shell. But when I add
a cron job to perform the execution of the scripts, it's not working, although
it logs them in cron log:

    
    
    Feb 25 10:21:00 Liubous-MacBook-Pro.local /usr/sbin/cron[43055]: (yudasinal1) CMD (/Users/path_to_script)
    

I tried adding a cronjob like this:

    
    
    DJANGO_SETTINGS_MODULE=project.settings
    * * * * * /Users/path_to_csv/test_subprocess.py
    

Where in the actual script I added `#!/usr/bin/env python` at the top of the
file.

As well as I tried adding this cronjob:

    
    
    DJANGO_SETTINGS_MODULE=project.settings
        * * * * * python /Users/path_to_csv/test_subprocess.py
    

All of them are logged into cron log, but unfortunately, the actual functions
are not being executed.

Any help would be appreciated!


Answer: # Step 1: Add Shebang to script

Unix scripts use a line called
"[Shebang](https://en.wikipedia.org/wiki/Shebang_%28Unix%29)"

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](http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-
under-linux-or-unix-oses/) 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.")
    

