I have a python script with #!/usr/bin/python in the first line. I can run it from CLI with python myScp.py.
But as part of cron script. The python script fails to run. The cron is tested, runs python script and can write to /tmp/crontest.txt
It seems that there is a directory problem. I tested with os.getcwd(). Its correct...Just when cron runs the script it throws an error. Running from CLI: /usr/bin/python myScp.py throws the same error.
Traceback (most recent call last):
File "/myScp.py", line 31, in <module>
execfile(dn2 + 'anotherScpt.py')
IOError: [Errno 2] No such file or directory: './anotherScpt.py'
2 Answers 2
Our preferred way is to specify explicitly the working dir as well in the crontab entries:
0 0 * * * cd /my/project; /opt/python-2.7/bin/python bin/myscript.py
Comments
Given the error, your problem is that you are relying on the program being in a particular directory to execute another file.
When you run the program in the directory it is in, it can find the file - when you (or cron) runs it outside that directory, it can't find that file. You need to put the file somewhere the script can find it, use an absolute path, or find the location of the script in the program.
#!/usr/bin/env pythoninstead - this should be better at getting the right path regardless of system setup. Also, try executing the file with./myScp.pyas that is what cron will essentially be doing.dn2?./refers to current directory, and I'm quite positive that you're assuming it to be something else thancronactually uses.