Mercurial > templog
comparison web/atomicfile.py @ 191:8318d50d766d
gets current params
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Tue, 11 Feb 2014 22:10:32 +0800 |
parents | |
children | 6dd157a12035 |
comparison
equal
deleted
inserted
replaced
189:101c66da848d | 191:8318d50d766d |
---|---|
1 import os | |
2 import time | |
3 import fcntl | |
4 import sys | |
5 | |
6 class AtomicFile(object): | |
7 DELAY = 0.5 | |
8 def __init__(self, name): | |
9 self.name = name | |
10 | |
11 def write(self, data, timeout = 5): | |
12 try: | |
13 end = time.time() + timeout | |
14 with open(self.name, "r+") as f: | |
15 while timeout == 0 or time.time() < end: | |
16 try: | |
17 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
18 except IOError: | |
19 time.sleep(DELAY) | |
20 continue | |
21 | |
22 f.write(data) | |
23 return True | |
24 | |
25 except IOError, e: | |
26 print>>sys.stderr, e | |
27 | |
28 return False | |
29 | |
30 def read(self, timeout = 5): | |
31 try: | |
32 end = time.time() + timeout | |
33 with open(self.name, "r") as f: | |
34 while timeout == 0 or time.time() < end: | |
35 try: | |
36 fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB) | |
37 except IOError: | |
38 time.sleep(DELAY) | |
39 continue | |
40 | |
41 return f.read() | |
42 | |
43 except IOError, e: | |
44 print>>sys.stderr, e | |
45 | |
46 return None |