简体   繁体   English

Python中的Crontab创建了cron作业,但不运行脚本

[英]Crontab in Python creates cron job, but doesn't run script

Not sure what I'm doing wrong whether it's the code, the directory, or something else. 不知道我做错了是代码,目录还是别的什么。 Please help! 请帮忙!

from crontab import CronTab

my_cron = CronTab(user='bgoldberg')
job = my_cron.new(command='python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py')
job.minute.every(1)
my_cron.write()

And here's the writeDate.py script: 这是writeDate.py脚本:

import datetime

with open('dateInfo.txt','a') as outFile:
    outFile.write('\n' + str(datetime.datetime.now()))

The writeDate.py script just writes the current timestamp to a txt file and it works fine when run separately. writeDate.py脚本只是将当前时间戳写入txt文件,并且单独运行时它可以正常工作。 When I run python scheduleCron.py, it runs without error but it seems that it's not running the writeDate.py script because no txt file is created. 当我运行python scheduleCron.py时,它运行没有错误,但它似乎没有运行writeDate.py脚本,因为没有创建txt文件。 When I enter crontab -l it correctly shows the job that was created: ***** python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py 当我输入crontab -l时,它正确显示了创建的作业:***** python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py

Not sure what I'm doing wrong... 不知道我做错了什么......

This is a cron "gotcha". 这是一个cron“gotcha”。 Cron uses the command Cron使用该命令

python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py

which you expect to write to your current working directory, but cron will write to /var/log/syslog or some variation of this by default. 您希望写入当前工作目录,但cron将默认写入/var/log/syslog或其中的一些变体。 It is trying to write to some place you don't have the permissions to (but it won't die), so you need to specifiy the absolute path of your output file. 它试图写入你没有权限的某个地方(但它不会死),所以你需要指定输出文件的绝对路径。

changing your line in writeDate.py to write to an absolute path: 更改writeDate.py的行以写入绝对路径:

with open('/Users/bgoldberg/dateinfo.txt', 'a') as outFile:

will solve your problem. 会解决你的问题。

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

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