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