Search code examples
pythoncron

Relative paths in scripts executed by cron jobs


I'm setting up my first cron job and it's not working. I think the problem may be a relative path issue.

Given cron job:

*/1 * * * * python2.7 /home/path/to/my/script/my_script.py

and my_script.py:

import sqlite3
db = sqlite3.connect('my_db.db')
cur = db.cursor()
...

How do I make sure that my_script.py looks for my_db.db in /home/path/to/my/script/ (the same directory that houses my_script.py) and not whatever directory crontab lives?

Other suggestions for troubleshooting are also welcome.

Note - I think the issue may be a path issue because when I try running my_script.py using python2.7 /home/path/to/my/script/my_script.py from any location other than /home/path/to/my/script/, I get an "unable to open database" error.


Solution

  • import sqlite3
    import os
    
    dir_path = os.path.dirname(os.path.abspath(__file__))
    
    db = sqlite3.connect(os.path.join(dir_path, 'my_db.db'))
    cur = db.cursor()
    ...
    

    Remember that Python's os.path module is your best friend when manipulating paths.