我试图在python脚本中使用crontab的内容。我想用python做任何事。最后,我希望获取crontab的内容,将其转换为临时文本文件,读取文本文件的行并对其进行操作。
有任何方法可以使用crontab文件的内容并像文本文件一样操作它吗?
我已经查看了子流程模块,但不太确定这是否是正确的解决方案.
注意:我并不试图以任何方式编辑crontab,我只是尝试在我的python中读取和操作它。最后,crontab将保持不变。我只需要包含在crontab中的信息来处理。
发布于 2016-07-25 13:43:47
如果您要尝试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()。
发布于 2018-04-18 07:57:17
当您试图更改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")此代码将有助于删除前一天的任务。我想这会对你有帮助。
https://stackoverflow.com/questions/38569365
复制相似问题