Sometimes we just need a single instance of the python script to run at a time. Meaning, the python script itself should detects whether any instances of himself are still running and act accordingly.
Well, how to do it?
The idea is simple, the first instance of the python script will open a file, and lock it. Therefore when the consequent instances try to lock the file, it will fails.
The code is simple too.
import fcntl def lockFile(lockfile): fp = open(lockfile, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: return False return True
The function will try to lock the file specified by me, if it success, return True, else return False.
From any point of my codes, I’ll do
if not lockFile(".lock.pod"): sys.exit(0)