Package gluon :: Module portalocker
[hide private]
[frames] | no frames]

Source Code for Module gluon.portalocker

 1  # portalocker.py - Cross-platform (posix/nt) API for flock-style file locking. 
 2  #                  Requires python 1.5.2 or better. 
 3   
 4  """Cross-platform (posix/nt) API for flock-style file locking. 
 5   
 6  Synopsis: 
 7   
 8     import portalocker 
 9     file = open("somefile", "r+") 
10     portalocker.lock(file, portalocker.LOCK_EX) 
11     file.seek(12) 
12     file.write("foo") 
13     file.close() 
14   
15  If you know what you're doing, you may choose to 
16   
17     portalocker.unlock(file) 
18   
19  before closing the file, but why? 
20   
21  Methods: 
22   
23     lock( file, flags ) 
24     unlock( file ) 
25   
26  Constants: 
27   
28     LOCK_EX 
29     LOCK_SH 
30     LOCK_NB 
31   
32  I learned the win32 technique for locking files from sample code 
33  provided by John Nielsen <nielsenjf@my-deja.com> in the documentation 
34  that accompanies the win32 modules. 
35   
36  Author: Jonathan Feinberg <jdf@pobox.com> 
37  Version: $Id: portalocker.py,v 1.3 2001/05/29 18:47:55 Administrator Exp $ 
38  """ 
39   
40  import os 
41   
42  if os.name == 'nt': 
43          import win32con 
44          import win32file 
45          import pywintypes 
46          LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK 
47          LOCK_SH = 0 # the default 
48          LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY 
49          # is there any reason not to reuse the following structure? 
50          __overlapped = pywintypes.OVERLAPPED() 
51  elif os.name == 'posix': 
52          import fcntl 
53          LOCK_EX = fcntl.LOCK_EX 
54          LOCK_SH = fcntl.LOCK_SH 
55          LOCK_NB = fcntl.LOCK_NB 
56  else: 
57          print 'warning, this device does not support file locking' 
58          LOCK_EX = None 
59          LOCK_SH = None 
60          LOCK_NB = None 
61   
62  if os.name == 'nt': 
63 - def lock(file, flags):
64 hfile = win32file._get_osfhandle(file.fileno()) 65 win32file.LockFileEx(hfile, flags, 0, 0x7fff0000, __overlapped)
66
67 - def unlock(file):
68 hfile = win32file._get_osfhandle(file.fileno()) 69 win32file.UnlockFileEx(hfile, 0, 0x7fff0000, __overlapped)
70 71 elif os.name =='posix':
72 - def lock(file, flags):
73 fcntl.flock(file.fileno(), flags)
74
75 - def unlock(file):
76 fcntl.flock(file.fileno(), fcntl.LOCK_UN)
77 78 else:
79 - def lock(file, flags): pass
80 - def unlock(file): pass
81 82 if __name__ == '__main__': 83 from time import time, strftime, localtime 84 import sys 85 86 log = open('log.txt', "a+") 87 lock(log, LOCK_EX) 88 89 timestamp = strftime("%m/%d/%Y %H:%M:%S\n", localtime(time())) 90 log.write( timestamp ) 91 92 print "Wrote lines. Hit enter to release lock." 93 dummy = sys.stdin.readline() 94 95 log.close() 96