简体   繁体   English

使用 cron 作业运行 python 脚本

[英]Running python script using a cron job

Ok so I am trying to run a python script every 3 hours using cron, but I think it's not working.好的,所以我尝试使用 cron 每 3 小时运行一次 python 脚本,但我认为它不起作用。 I know this because my script should produce some csv files and I cannot find them anywhere or the logs, plus my script is also reading from another file like (which I think is part of the issue):我知道这一点是因为我的脚本应该生成一些 csv 文件并且我无法在任何地方或日志中找到它们,而且我的脚本也在从另一个文件中读取(我认为这是问题的一部分):

with open('json_file.json') as f:
...

so if I try to run my script from a different directory with所以如果我尝试从不同的目录运行我的脚本

> python ~/my_working_dir/my_script.py

I get a FileNotFoundError我得到一个 FileNotFoundError

FileNotFoundError: [Errno 2] No such file or directory: 'json_file.json' FileNotFoundError:[Errno 2] 没有这样的文件或目录:'json_file.json'

my job goes something like this:我的工作是这样的:

SHELL=/usr/bin/zsh
0 */3 * * * python ~/my_working_dir/my_script.py > ~/my_working_dir/cronlogs/cron.log

I have little experience with crontab so I am not sure about the source of the problem, but my first guess is that I need to add some path somewhere我对 crontab 的经验很少,所以我不确定问题的根源,但我的第一个猜测是我需要在某处添加一些路径

Hope someone could help希望有人能帮忙

I think would be better if you gave open() a full path for that file.我认为如果你给 open() 一个该文件的完整路径会更好。 I would specify the full path to python as well.我也会指定 python 的完整路径。

1 */12 * * * /usr/bin/python3 /root/telesend.py >> /root/cron.log 2>&1

this is my example which is working perfectly well take a look at link for correct schedule expressions这是我的示例,它运行良好查看链接以获取正确的时间表表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM