我编写了一个 python 脚本来运行某些 cron 作业并使用 crontab 来执行相同的操作。以下是代码片段:import osimport inspectfrom crontab import CronTabdef add_cron_job(scripts_list,frequency): my_cron = CronTab(user='simrat') for script in scripts_list: if not cron_exists(my_cron,script): command = 'python {}'.format(script) job = my_cron.new(command=command, comment=script) job.minute.every(frequency) my_cron.write()def cron_exists(my_cron, script): for job in my_cron: if job.comment == script: return True return Falseif __name__ == "__main__": #Frequency of every 1 minute test_script = ['test1.py', 'test2.py'] add_cron_job(test_script,1) #Frequency of every 1 day test_script2 = ['test3.py'] add_cron_job(test_script2,1440)以下是 'crontab -e' 的输出(注意添加了额外的空格)* * * * * python test1.py # test1.py* * * * * python test2.py # test2.py*/1440 * * * * python test3.py # test3.py当我重新运行 python cron_job 脚本时,它会以某种方式禁用最后一个 cron_job(test3.py),以下是 crontab 文件的输出:* * * * * python test1.py # test1.py* * * * * python test2.py # test2.py# DISABLED LINE# */1440 * * * * python test3.py # test3.py*/1440 * * * * python test3.py # test3.py连同它在控制台上抛出的错误:No handlers could be found for logger "crontab"所以我的问题是3折:为什么运行 my_cron.write() 时命令顶部有额外的空间?为什么它会禁用最后一个 cron 作业而不是忽略它,因为它已经存在(def cron_exits 应该已经处理好了)抛出的错误有什么意义?
1 回答

慕雪6442864
TA贡献1812条经验 获得超5个赞
我运行了您的代码,并在第二次运行时出现以下错误:
'1440', not in 0-59 for Minutes
我将 1440 更改为 14 并多次运行代码。并且每次都找到相同的代码(不删除)
* * * * * python test1.py # test1.py
* * * * * python test2.py # test2.py
*/14 * * * * python test3.py # test3.py
我还没有阅读完整CronTab的代码,但很明显他们在读取现有的 cron 命令期间放置了一些验证器,但他们在写入期间没有验证它。
我也add_cron_job用不同的参数调用,发现每次my_cron.write()调用它都在添加一个新行。这不是一个错误,而是一个功能。
最后 No handlers could be found for logger "crontab"是日志记录问题。试试这个Crontab Logger 问题
添加回答
举报
0/150
提交
取消