Grammar
[adesklets.git] / test / flock.py
blob003682459a979b5441e0f6d2547f173048f4f30d
1 """
2 flock.py -- Simple exclusive lock fcntl test program in Python.
4 Usage: python /path/to/lock_test.py
6 The script will try to open(create if needed), then lock a 'lock_test.txt'
7 file in the current working directory, write its PID in it, then wait for
8 the user to press enter, then release the lock, close the file and exit.
10 Tested on both stock Python 2.3.5 and Python 2.4.2
11 """
12 from sys import stdout, exc_info
13 from traceback import print_exception
14 from os import getcwd, getpid
15 from os.path import join
16 from fcntl import lockf, LOCK_UN, LOCK_EX
18 try:
19 filename = join(getcwd(),'lock_test.txt')
20 print 'Opening or creating "%s"...' % filename,
21 f = file(filename,'a')
22 print 'ok'
23 print 'Acquiring lock...',
24 stdout.flush()
25 lockf(f,LOCK_EX)
26 print 'ok'
27 print 'Writing pid (%d)...' % getpid(),
28 print >> f, "PID:", getpid()
29 print 'ok'
30 raw_input('[Press enter to exit]')
31 print 'Releasing lock...',
32 lockf(f,LOCK_UN)
33 print 'ok'
34 print 'Closing file...',
35 f.close()
36 print 'ok'
37 except:
38 print 'failed'
39 print '='*80
40 print_exception(*exc_info())
41 print '='*80