python - How to get the "result" from a contextmanager using 'with' -
i found demo of file locking class (here: https://groups.google.com/forum/#!topic/pug-pe/mqr7kx-cenu), don't quite understand mechanics of using it.
@contextmanager def filelock(lock_file): if os.path.exists(lock_file): print 'only 1 script can run @ once. '\ 'script locked %s' % lock_file sys.exit(-1) else: open(lock_file, 'w').write("1") try: yield finally: os.remove(lock_file)
i believe says "if file passed in not exist, open it. when done, delete it.
the demonstrated use is:
with filelock('/tmp/my_script.lock'): print "i here , sleeping 10 sec..." time.sleep(10)
and works correctly - if run script once see "i here , sleeping 10 sec...", , if run again within 10 seconds, see "only 1 script can run @ once. script locked /tmp/my_script.lock". however, use file lock, 1 typically want "wait until lock obtained" before doing something. however, 'sys.exit()' seems prevent that. seems want wrap 'with' in while loop somehow? like:
while fileislocked: filelock('/tmp/my_script.lock'): # try lock print "i here , sleeping 10 sec..." time.sleep(10)
but don't understand how return value filelock. can please explain how this?
you should use following:
@contextmanager def filelock(lock_file): while os.path.exists(lock_file): print 'only 1 script can run @ once. '\ 'script locked %s' % lock_file time.sleep(1) open(lock_file, 'w').write("1") try: yield finally: os.remove(lock_file)
this directly answers declared need. otoh method buggy because there explicit race condition between checking file existence , opening one. more stable approach should use o_excl
ensure file didn't exist during creation, or flock
use locking on file contents, not presence. also, kernel-level ipc can used (posix semaphores, sysv semaphores, etc.)
Comments
Post a Comment