Relative paths in scripts executed by cron jobs

I am setting up my first cron job and it does not work. I think the problem may be a relative path problem.

Cron task:

*/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 to make sure my_script.py looks for my_db.db in /home/path/to/my/script/ (the same directory where my_script.py is located) and that no crontab directory exists?

Other troubleshooting suggestions are also welcome.

Note. I think the problem may be a path problem, because when I try to run 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 error "cannot open database".

+8
python cron crontab
source share
2 answers
 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 the Python os.path module is your best friend when manipulating paths.

+12
source share

you can do it a little differently:

 os.chdir(os.path.dirname(os.path.abspath(__file__))) db = sqlite3.connect('my_db.db') 

using chdir will allow you to execute the script in a local directory and allow you to keep all local links intact if you have several options that can save you time :)

+1
source share

All Articles