Hands-on Lab·Python Automation for IT
Python Locking and Single-Instance Scripts
A cron job that sometimes takes longer than its interval will eventually run twice at once. The obvious fix - a lock file - has a failure mode that is worse than the problem: a run killed while holding it locks the job out permanently. This guide shows the collision, the stale lock, and `fcntl.flock`, which the kernel releases when the holder dies no matter how it died.
OS and Process Automation Guide 22 of 39 Intermediate
- Python3.14.4
- Control nodeUbuntu 26.04 LTS
- Managed hostsRHEL 10.0
- requests2.34.2
- paramiko5.0.0
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
- TimeAbout 18 min
- Reviewed24 August 2026
Written against the versions above. `fcntl` is Unix-only and always has been; on Windows the equivalent is `msvcrt.locking`. `unlink(missing_ok=True)` needs Python 3.8.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
Before you start
-
Two runs at once
-
A lock file claimed without a race
-
And what happens when a run dies holding it
-
A lock the kernel releases for you
-
The file left behind is harmless
-
Even when the holder is killed
-
A context manager, so it cannot be forgotten