【问题标题】:Using Crontab in a Python Script在 Python 脚本中使用 Crontab
【发布时间】:2016-11-28 21:22:49
【问题描述】:

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

有什么方法可以使用 crontab 文件的内容并像处理文本文件一样操作它???

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

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

【问题讨论】:

  • 到目前为止你尝试过什么? this question 的答案列出了一些您可以用来解析 crontab 的 Python 包。

标签: python subprocess crontab


【解决方案1】:

如果您尝试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 中,它将返回二进制数据,因此您需要 crontab = crontab.decode()

【讨论】:

  • 这与我正在寻找的内容非常接近。可以说,我不想运行命令“crontab -l”,而是想运行“crontab -u root -l”,我会将子进程命令更改为 subprocess.check_output(['crontab', '-u', 'root' , ' -l'])?
  • 此外,crontab.decode() 是否允许我将 crontab 视为文本文件?
【解决方案2】:

当您尝试更改 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")

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

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 2021-05-25
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多