1 """
2 Platform-independent file locking. Inspired by and modeled after zc.lockfile.
3 """
4
5 import os
6
7 try:
8 import msvcrt
9 except ImportError:
10 pass
11
12 try:
13 import fcntl
14 except ImportError:
15 pass
16
17
19
20 "Could not obtain a lock"
21
22 msg = "Unable to lock %r"
23
26
27
29
30 "Could not release a lock"
31
32 msg = "Unable to unlock %r"
33
34
35
37
38 """
39 A default, naive locking implementation. Always fails if the file
40 already exists.
41 """
42
44 self.path = path
45 try:
46 fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
47 except OSError:
48 raise LockError(self.path)
49 os.close(fd)
50
53
56
57
59
60 """
61 An abstract base class for platform-specific locking.
62 """
63
65 self.path = path
66
67 try:
68
69 self.fp = open(path, 'r+')
70 except IOError:
71
72
73
74
75 self.fp = open(path, 'a+')
76
77 try:
78 self._lock_file()
79 except:
80 self.fp.seek(1)
81 self.fp.close()
82 del self.fp
83 raise
84
85 self.fp.write(" %s\n" % os.getpid())
86 self.fp.truncate()
87 self.fp.flush()
88
95
97 """
98 Attempt to remove the file
99 """
100 try:
101 os.remove(self.path)
102 except:
103 pass
104
105
106
107
108
109
111 """Attempt to obtain the lock on self.fp. Raise UnlockError if not
112 released."""
113
114
130
131 if 'msvcrt' in globals():
132 LockFile = WindowsLockFile
133
134
143
144
145
146 if 'fcntl' in globals():
147 LockFile = UnixLockFile
148