Last active
October 28, 2016 08:24
-
-
Save vovaprog/5fa47e5f3b403a3ddab3ddef69444c15 to your computer and use it in GitHub Desktop.
create or open file for exclusive write
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import errno | |
import fcntl | |
def open_file_write_exclusive(file_name): | |
""" | |
If file is available - returns file object. | |
If file is locked - returns None. | |
If error occured - throws error. | |
Truncates opened file. | |
""" | |
fl = open(file_name, 'w') | |
try: | |
fcntl.flock(fl, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except IOError as e: | |
if e.errno == errno.EAGAIN: | |
return None | |
else: | |
raise | |
fl.truncate(0) | |
return fl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment