Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

cron - FileNotFoundError while using crontab to run Python script

I'm totally lost here. I'm trying to create a scheduler to run python script on my Mac, but I'm getting the following error:

Traceback (most recent call last):
  File "/Users/Root/Desktop/Project/Data/script.py", line 148, in <module>
    run(
  File "/Users/Root/Desktop/Project/Data/script.py", line 121, in run
    config = get_config("config")
  File "/Users/Root/Desktop/Project/Data/config/__init__.py", line 3, in get_config
    with open(f"config/{config_type}.json", "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'config/config.json'

So crontab convinces me that there is no such file or a directory, which is not true. I can run my script manually without errors. My crontab is:

00 19 21 1-12 * /Library/Frameworks/Python.framework/Versions/3.9/bin/python3/ /Users/Root/Desktop/Project/Data/script.py >> /Users/Root/Desktop/Project/Data/cron.txt 2>&1

What am I doing wrong? I'd be grateful for any help!

And is this possible without changing the relative path to an absolute path? I am aware of this solution

question from:https://stackoverflow.com/questions/65831700/filenotfounderror-while-using-crontab-to-run-python-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume crontab's cwd (Current Working Directory) is not same as where the script is stored.

this would solve your problem:

import os
script_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_dir)

You can get the directory where you script is by calling "os.path.dirname(os.path.realpath(file))"

if you change the current working directory "os.chdir(...dir...)" you can access you config/config.json by relative path,

Otherwise you will have to use a absolute path

Try running this and check your output file:

import os
script_dir = os.path.dirname(os.path.realpath(__file__))
print (os.getcwd())
print(script_dir)
os.chdir(script_dir)
print (os.getcwd())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...