Wrong path causes the python program to run using crontab

I have a script in python under Linux that needs to determine the current working directory. The part of the program that does this:

import os
cwd = os.getcwd()
print cwd

      

When I run the program, it gives the correct answer:

/home/johny/LST/CT

      

But when I run it using crontab it gives me this:

/home/johny

      

Even when I put it in deeper folders the same path comes out. Does anyone know what the problem is?

+3


source to share


2 answers


cron is probably just installing into your home directory. If you need your script to run in a specific directory, consider using something like

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

      



at the top of your script, even though your script shouldn't really care where it's running from. All file paths in a script must be script-specific using something like:

scriptdir = os.path.dirname(os.path.abspath(__file__))

mypath = os.path.join(scriptdir, 'data', 'mfile.dat')

... etc ...

      

+2


source


In your crontab file, run:



1 0 * * * cd /home/johny/LST/CT; python your_script.py

      

+3


source







All Articles