I'm on an OSX machine using UNIX. I have a Python program that I want to run every hour or so, so I've set up a basic cron command in my editor:
0 * * * * python Documents/workspace/programfolder/src/ProgramToRun.py
I haven't actually tried this yet because I'm already running into issues. I've tried to just run the python Documents/workspace/programfolder/src/ProgramToRun.py command from my home directory, but the script fails to find any of the files in its directory that it depends upon. It is as though the program is somehow running in my home directory and cannot find any of its dependencies. If I cd into the folder where the program is located and do python ProgramToRun.py, it works fine. So my question is how can I get cron to treat this program like I'm running it from its directory? And would the directory I've given even work, or would I need to give something more absolute like /Users/MyName...etc.?
You could do this in one of two ways:
First way:
cd into the dir containing the python script and the dependencies and run it from there as follows:
(cd /Users/username/Documents/workspace/programfolder/src/ && python ProgramToRun.py)
Here, the parens invoke a "subshell". Think of it like a contiguous session in which all commands are run. The && functions as a ;, but doesn't execute the next command if the previous command fails
Second way:
Add Documents/workspace/programfolder/src/ to the PYTHONPATH inside ProgramToRun.py as follows:
import sys
sys.path.append("/Users/username/Documents/workspace/programfolder/src/")
Hope this helps
Put this at the top of you script before you start doing relative stuff.
import os
scriptdir = os.path.dirname(os.path.abspath(__file__))
os.chdir(scriptdir)
it also may be a symptom that your script isn't actually trying to resolve paths etc relative to the script in the first place. Scripts shouldn't rely on the user running the script from the same directory as the script.
I usually use scriptdir to find stuff relative to the script e.g.
open(os.path.join(scriptdir, 'data', 'someconfig.cfg')) instead of open(os.path.join('data', 'someconfig.cfg'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With