Use fcntl.flock to Ensure Only One Instance of a Python Script Is Running 發表於 2017-02-09 | 123456789101112131415161718192021222324#!/usr/bin/env python3import fcntlfrom os import removefrom os.path import splitextfrom time import sleepdef main(): lock_file = '{}.lock'.format(splitext(__file__)[0]) with open(lock_file, 'w') as lock_fp: try: fcntl.flock(lock_fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: print('Script has been running.') return else: print('Script starts to run.') sleep(10) print('Done!') remove(lock_file)if __name__ == '__main__': main() Note that this code doesn’t works on Windows. References: https://docs.python.org/3/library/fcntl.html#fcntl.flock