Code

merge from maintenance branch
[roundup.git] / roundup / backends / portalocker.py
1 # portalocker.py - Cross-platform (posix/nt) API for flock-style file locking.
2 #                  Requires python 1.5.2 or better.
4 # ID line added by richard for Roundup file tracking
5 # $Id: portalocker.py,v 1.2 2002-10-03 06:56:29 richard Exp $
7 """ Cross-platform (posix/nt) API for flock-style file locking.
9 Synopsis:
11    import portalocker
12    file = open("somefile", "r+")
13    portalocker.lock(file, portalocker.LOCK_EX)
14    file.seek(12)
15    file.write("foo")
16    file.close()
18 If you know what you're doing, you may choose to
20    portalocker.unlock(file)
22 before closing the file, but why?
24 Methods:
26    lock( file, flags )
27    unlock( file )
29 Constants:
31    LOCK_EX
32    LOCK_SH
33    LOCK_NB
35 I learned the win32 technique for locking files from sample code
36 provided by John Nielsen <nielsenjf@my-deja.com> in the documentation
37 that accompanies the win32 modules.
39 Author: Jonathan Feinberg <jdf@pobox.com>
40 Version: Id: portalocker.py,v 1.3 2001/05/29 18:47:55 Administrator Exp 
41          **un-cvsified by richard so the version doesn't change**
42 """
43 import os
45 if os.name == 'nt':
46         import win32con
47         import win32file
48         import pywintypes
49         LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
50         LOCK_SH = 0 # the default
51         LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
52         # is there any reason not to reuse the following structure?
53         __overlapped = pywintypes.OVERLAPPED()
54 elif os.name == 'posix':
55         import fcntl
56         LOCK_EX = fcntl.LOCK_EX
57         LOCK_SH = fcntl.LOCK_SH
58         LOCK_NB = fcntl.LOCK_NB
59 else:
60         raise RuntimeError("PortaLocker only defined for nt and posix platforms")
62 if os.name == 'nt':
63         def lock(file, flags):
64                 hfile = win32file._get_osfhandle(file.fileno())
65                 win32file.LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped)
67         def unlock(file):
68                 hfile = win32file._get_osfhandle(file.fileno())
69                 win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)
71 elif os.name =='posix':
72         def lock(file, flags):
73                 fcntl.flock(file.fileno(), flags)
75         def unlock(file):
76                 fcntl.flock(file.fileno(), fcntl.LOCK_UN)
78 if __name__ == '__main__':
79         from time import time, strftime, localtime
80         import sys
81         import portalocker
83         log = open('log.txt', "a+")
84         portalocker.lock(log, portalocker.LOCK_EX)
86         timestamp = strftime("%m/%d/%Y %H:%M:%S\n", localtime(time()))
87         log.write( timestamp )
89         print "Wrote lines. Hit enter to release lock."
90         dummy = sys.stdin.readline()
92         log.close()