Skip to content

Instantly share code, notes, and snippets.

@vovaprog
Last active October 28, 2016 08:24
Show Gist options
  • Save vovaprog/5fa47e5f3b403a3ddab3ddef69444c15 to your computer and use it in GitHub Desktop.
Save vovaprog/5fa47e5f3b403a3ddab3ddef69444c15 to your computer and use it in GitHub Desktop.
create or open file for exclusive write
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