Created
March 8, 2019 15:26
-
-
Save kgaughan/98face12717898ce08652242f53befcd to your computer and use it in GitHub Desktop.
Using a python script as its own mutex to prevent it executing concurrently with multiple instances of itself
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import contextlib | |
import fcntl | |
import sys | |
import time | |
class MutexException(Exception): | |
""" | |
Failed to lock a file. | |
""" | |
@contextlib.contextmanager | |
def mutex(filename): | |
""" | |
Using file identified by filename as mutex | |
:param filename: The file we are going to use as mutex | |
""" | |
with open(filename, 'r') as fh: | |
try: | |
try: | |
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except IOError: | |
raise MutexException("Failed to lock {}".format(filename)) | |
yield | |
finally: | |
fcntl.flock(fh, fcntl.LOCK_UN) | |
def main(): | |
print("Started! Doing work...") | |
time.sleep(5) | |
print("All done!") | |
return 0 | |
if __name__ == "__main__": | |
try: | |
with mutex(__file__): | |
sys.exit(main()) | |
except MutexException: | |
print("{} is already running, exiting".format(__file__), | |
file=sys.stderr) | |
sys.exit(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment