我编写了一个 python 脚本来运行某些 cron 作业并使用 crontab 来执行相同的操作。
以下是代码片段:
import os
import inspect
from crontab import CronTab
def 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 False
if __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 应该已经处理好了)
抛出的错误有什么意义?
慕雪6442864
相关分类