Run process with lockfile¶
Overview¶
Look over this example
run-with-lock.py
import fcntl
import os
import sys
import time
# Use the script name to generate a unique lock file
LOCKFILE = f"/tmp/{os.path.basename(__file__)}.lock"
def work() -> None:
time.sleep(999)
if __name__ == "__main__":
try:
# Open a file and acquire an exclusive lock
with open(LOCKFILE, "w") as lockfile:
fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
print("Acquired lock, running script...")
# Main script logic here
work()
except BlockingIOError:
print("Another instance is running. Exiting.")
sys.exit(1)