Reputation: 501
I am trying to use the contents of a crontab inside a python script. I want to do everything using python. In the end I hope to take the contents of the crontab, convert it to a temporary textfile, read in the lines of the text file and manipulate it.
Is there any way i can use the contents of the crontab file and manipulate it as if it were a text file???
I've looked into the subprocess module but am not too sure if this is the right solution....
NOTE: I am not trying to edit the crontab in any way, I am just trying to read it in and manipulate it within my python code. In the end, the crontab will remain the same. I just need the information contained inside the crontab to mess with.
Upvotes: 0
Views: 550
Reputation: 211
As you are trying to change the crontab entry (e.g.- deleting the completed tasks):
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")
This code will help to delete the previous day tasks. I think this will help you.
Upvotes: 0
Reputation: 51907
If you were to try crontab -h
, which is usually the help option, you'll get this:
$ 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
The line to note is the one that says -l list user's crontab
. If you try that, you see that it lists out the contents of one's crontab file. Based on that, you can run the following:
import subprocess
crontab = subprocess.check_output(['crontab', '-l'])
And crontab
will contain the contents of one's crontab. In Python3 it will return binary data so you'll need crontab = crontab.decode()
.
Upvotes: 2