How Do You Make Python Automation Scripts Reliable Enough to Run Unattended?
To make a Python automation script reliable enough to run unattended, give it four things: retries with backoff for flaky calls, idempotent steps so a rerun never duplicates work, structured logging so you can see what happened, and a scheduler (cron or systemd timer) with a lock so runs never overlap.
The sections below show each piece in plain Python.
Why do unattended scripts fail?
A script that works at your desk fails on a server for boring reasons: a network call times out, the previous run is still going, a file is half-written, or nobody sees the error. Reliability is mostly about handling these cases deliberately.
How do you add retries with backoff?
import time, random, functools
def retry(times=4, base=1.0, exceptions=(Exception,)):
def deco(fn):
@functools.wraps(fn)
def wrapper(*a, **kw):
for attempt in range(1, times + 1):
try:
return fn(*a, **kw)
except exceptions as e:
if attempt == times:
raise
delay = base * 2 ** (attempt - 1) + random.random()
time.sleep(delay)
return wrapper
return deco
@retry(times=4, exceptions=(TimeoutError, ConnectionError))
def fetch_report():
...
Only retry errors that are likely temporary. Retrying a bug just hides it.
How do you make steps idempotent?
Record what is done, and skip it next time. A small SQLite table is enough:
import sqlite3
db = sqlite3.connect("state.db")
db.execute("CREATE TABLE IF NOT EXISTS done (id TEXT PRIMARY KEY)")
def process(item_id):
if db.execute("SELECT 1 FROM done WHERE id=?", (item_id,)).fetchone():
return
do_work(item_id)
db.execute("INSERT INTO done VALUES (?)", (item_id,))
db.commit()
Write output files to a temporary name and rename them when finished, so a crash never leaves a partial file.
How do you log so failures are visible?
import logging
logging.basicConfig(
filename="job.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("job")
try:
main()
except Exception:
log.exception("job failed")
raise
A non-zero exit code lets the scheduler or a monitor notice the failure.
How do you stop runs from overlapping?
import fcntl, sys
lock = open("/tmp/job.lock", "w")
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
sys.exit("previous run still active")
How do you schedule it?
A cron line is the simplest option:
*/15 * * * * cd /opt/job && /opt/job/venv/bin/python run.py
A systemd timer adds journald logs and restart control. Use absolute paths and a virtualenv either way.
FAQ
- Is cron good enough for production automation? For many jobs, yes, if you add locking, logging and exit codes as above.
- Should I use Celery or a queue instead? Use a queue when you need many parallel workers or user-triggered jobs. For periodic single jobs, cron is simpler.
- How do I know a job silently stopped running? Have it ping a heartbeat or write a last-success timestamp, and alert when that timestamp gets old.
- Should every exception be retried? No. Retry timeouts and connection errors; let logic errors fail loudly.
I'm Muhammad Afzal, a Python and Rust automation engineer. I build automation and backends at INDUS Web Agency.
Comments
No comments yet. Start the discussion.