use fcntl.flock to ensure only one instance of a python script is running

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import fcntl
from os import remove
from os.path import splitext
from time import sleep
def ():
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: