Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
Brian Goler Avatar asked May 02 '12 22:05

Brian Goler


People also ask

What path does crontab use?

When you create a crontab file, it is automatically placed in the /var/spool/cron/crontabs directory and is given your user name. You can create or edit a crontab file for another user, or root, if you have superuser privileges.

What is the use of * * * * * In cron?

* * * * * is a cron schedule expression wildcard, meaning your cron job should run every minute of every hour of every day of every month, each day of the week.

How do relative file paths work?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


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 Python's os.path module is your best friend when manipulating paths.

like image 107
ChristopheD Avatar answered Sep 27 '22 16:09

ChristopheD


you may want to do it a bit differently:

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

using chdir will allow to execute you script in local directory and allow you to keep all local references unchanged if you have more than one it may save you some time :)

like image 39
dymy Avatar answered Sep 27 '22 15:09

dymy