簡體   English   中英

在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中,它將返回二進制數據,因此您需要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")

此代碼將有助於刪除前一天的任務。 我認為這會對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM