You should use something like the following:
@contextmanager def FileLock(lock_file): while os.path.exists(lock_file): print 'Only one script can run at once. '\ 'Script is locked with %s' % lock_file time.sleep(1) open(lock_file, 'w').write("1") try: yield finally: os.remove(lock_file)
This directly answers your declared need. OTOH the method is very buggy because there is explicit race condition between checking file existence and opening one. A more stable approach should use O_EXCL
to ensure file didn't exist during creation, or flock
to use locking on the file contents, not its presence. Also, some kernel-level IPC can be used (Posix semaphores, SysV semaphores, etc.)