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
"""
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.path
fh = None
def test_lock(fname):
"""
Detect if file is locked.
"""
global fh
fh = open(fname, 'w')
try:
flock(fh.fileno(), LOCK_EX | LOCK_NB)
except Exception, ex:
return True
return False
def test_lock_and_exit(fname):
"""
If file is locked then terminate program.
"""
logging.debug('Trying to lock: %s' % fname)
if test_lock(fname):
logging.error(u'%s is locked so I must die!' % fname)
sys.exit()