Search code examples
pythoncron

Crontab not executing a Python script?


My python script is not running under my crontab.

I have placed this in the python script at the top:

#!/usr/bin/python

I have tried doing this:

chmod a+x myscript.py

Added to my crontab -e:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""

* * * * * /home/me/project/myscript.py

My /var/log/cron file says:

Sep 21 11:53:02 163-dhcp /USR/SBIN/CROND[2489]: (me) CMD (/home/me/project/myscript.py)

But my script is not running because when I check my sql database, nothing has changed. If I run it directly in the terminal like so:

python /home/me/project/myscript.py

I get the correct result.

This is the myscript.py:

#!/usr/bin/python

import sqlite3

def main():
    con = sqlite3.connect("test.db")

    with con:

        cur = con.cursor()

        cur.execute("CREATE TABLE IF NOT EXISTS testtable(Id INTEGER PRIMARY KEY, Name TEXT)")

        cur.execute("INSERT INTO testtable(Name) VALUES ('BoB')")

        cur.execute("SELECT * FROM testtable")

        print cur.fetchall()    

if __name__ == "__main__":
    main()

Per comments: Yes, /usr/bin/python exists. I can also run the python script directly using just /home/me/project/myscript.py. /usr/bin/python /home/me/project/myscript.py works. So I don't believe this is the cause?


Solution

  • What happens when you type

    /home/me/project/myscript.py into the shell?

    Can you explicitly use /usr/bin/python in your crontbb command?

    Can you either use an absolute path to your test.db or cd to the correct directory then execute your python script?

    This is helpful to have debug statements in your python and log some data. Crontab can be very tricky to debug.