coding utf-8 Лок файла Синтаксис om lock lock tmp test pid from fcntl

 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# -*- coding: utf-8 -*-
"""
Лок файла. Синтаксис: om.lock.lock('/tmp/test.pid')
"""
from fcntl import flock, LOCK_EX, LOCK_NB
import os
import sys
import logging
fh = None
log = logging.getLogger(__name__)
def main():
logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
lock(os.path.join(settings.VAR_ROOT, 'proxy_check_proxy.pid'))
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 lock(fname):
"""
If file is locked then terminate program else lock file.
"""
if set_lock(fname):
#~ log.debug('Locked: %s' % fname)
pass
else:
log.error(u'%s is already locked. Terminating.' % fname)
sys.exit()
if __name__ == "__main__":
main()