We know the crontab command is used for scheduled tasks in Linux.
I want to write a Python script. Its function is to receive some data (these data are related to crontab setting) and execute a 'crontab' command in order to reset the content of the user's crontab file.
I know how to execute external Linux commands in Python. But when you execute the crontab command (e.g. crontab -u xxx -e), you need to interact with an editor to modify the user's crontab file. (Suppose I don't know where the file is. For new users, crontab will generate a new file anyway. And I don't execute the command as the root user).
So the question is, how can I just execute crontab in Python? Is there any way to avoid interacting with an editor to modify the user's crontab file in Python?
My OS is ubuntu 14.01.
You could use python-crontab.
sudo -H pip install python-crontab
List system cron jobs:
from crontab import CronTab
cron = CronTab(tabfile='/etc/crontab', user=False) # system users cron
# cron = CronTab(user=True) # current users cron
# cron = CronTab(user='username') # other users cron
for job in cron:
print(job)
Create a new job:
job = cron.new(command='/foo/bar', comment='SomeID')
Enable / disable job:
job.enable()
job.enable(False)
Find an existing job by comment:
iter = cron.find_comment('ID or some text')
Remove Items::
cron.remove( job )
cron.remove_all('echo')
cron.remove_all(comment='foo')
cron.remove_all(time='*/2')
Clear entire cron of all jobs::
cron.remove_all()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With