Python Crontab API
python-crontab provides a Pythonic API to create, manage, read, and write crontab entries and entire crontab files, including user-specific and system-wide crontabs. As of version 3.3.0, it offers a unified `CronTab` class for all crontab manipulations, simplifying interaction with cron jobs from Python. The library is actively maintained with an irregular release cadence.
Warnings
- breaking Version 3.0.0 introduced significant breaking changes. The `Crontab` (system-wide) and `CrontabEntry` classes were removed/renamed. All crontab manipulations now happen through the unified `CronTab` class, with parameters like `user` or `tabfile` to specify the target crontab.
- gotcha Changes made to the `CronTab` object are not persisted to the actual crontab file until the `.write()` method is explicitly called. Forgetting to call `.write()` will result in no actual changes to the system's cron jobs.
- gotcha Running `python-crontab` to modify system or other user's crontabs often requires elevated privileges (e.g., `sudo`). Without proper permissions, operations like `my_cron.write()` might fail silently or raise permission errors.
- gotcha When finding jobs, methods like `find_command`, `find_comment`, or iteration (`for job in my_cron:`) return `CronItem` objects. Modifying these `CronItem` objects directly requires `my_cron.write()` to save the changes.
Install
-
pip install python-crontab
Imports
- CronTab
from crontab import CronTab
- CronTab
from crontab import CronTab
Quickstart
from crontab import CronTab
# Initialize crontab for the current user. Permissions might be needed.
# For system-wide crontabs, use CronTab(user='root') and ensure proper permissions.
my_cron = CronTab(user=True)
# Create a new cron job
job = my_cron.new(command='echo "Hello from cron!" >> /tmp/cron_test.log', comment='my_test_job')
job.minute().every(1) # Run every minute
# Iterate existing jobs (optional)
print('Existing jobs:')
for j in my_cron:
print(j)
# IMPORTANT: Write changes to the crontab file
my_cron.write()
print('Crontab updated. Check /tmp/cron_test.log in a minute.')
# To remove a job later (example):
# for job_to_remove in my_cron.find_comment('my_test_job'):
# my_cron.remove(job_to_remove)
# my_cron.write()