Provide functions for check if file is locked from fcntl import flock

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
Provide functions for check if file is locked.
"""
from fcntl import flock, LOCK_EX, LOCK_NB
import os.path
import sys
import logging
import os
fh = None
def set_lock(fname):
"""
Try to lock file and write PID.
Return the status of operation.
"""
global fh
fh = open(fname, 'w')
try:
flock(fh.fileno(), LOCK_EX | LOCK_NB)
except Exception, ex:
return False
else:
fh.write(str(os.getpid()))
fh.flush()
return True
def assert_lock(fname):
"""
If file is locked then terminate program else lock file.
"""
logging.debug('Trying to lock: %s' % fname)
if not set_lock(fname):
logging.error(u'%s is already locked. Terminating.' % fname)
sys.exit()