在 Python 脚本中使用 Crontab

Using Crontab in a Python Script

我正在尝试在 python 脚本中使用 crontab 的内容。我想使用 python 做所有事情。最后我希望把crontab的内容,转换成一个临时的文本文件,读入文本文件的行并进行操作。

有什么方法可以使用 crontab 文件的内容并将其当作文本文件来操作吗???

我查看了子流程模块,但不太确定这是否是正确的解决方案....

注意: 我没有尝试以任何方式编辑 crontab,我只是想读入它并在我的 python 代码中操作它。最后,crontab 将保持不变。我只需要 crontab 中包含的信息来搞乱。

如果您尝试 crontab -h,这通常是帮助选项,您将得到:

$ crontab -h
crontab: invalid option -- 'h'
crontab: usage error: unrecognized option
Usage:
 crontab [options] file
 crontab [options]
 crontab -n [hostname]

Options:
 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -x <mask>  enable debugging

Default operation is replace, per 1003.2

要注意的那一行是 -l list user's crontab。如果您尝试这样做,您会看到它列出了一个人的 crontab 文件的内容。基于此,您可以 运行 以下内容:

import subprocess

crontab = subprocess.check_output(['crontab', '-l'])

crontab将包含一个人的crontab的内容。在 Python3 中,它将 return 二进制数据,因此您需要 crontab = crontab.decode().

当您尝试更改 crontab 条目时(例如-删除已完成的任务):

import os
import datetime
os.system("crontab -l > new")
read_file = open("new","r")
write_file = open("new_edit","w")
today= datetime.datetime.now()
current_date = today.day
current_month = today.month
for lines in read_file:
        if lines=="\n":
                pass
        else:
                sep = lines.split(" ")
                if (current_date < int(sep[2]) and current_month == int(sep[3])):
                        write_file.write(lines)
write_file.close()
os.system("sudo mv new_edit /var/spool/cron/ec2-user")

此代码将有助于删除前一天的任务。我想这会对你有所帮助。