Advertisement
Guest User

Untitled

a guest
Oct 28th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. import os
  2. import errno
  3. import fcntl
  4.  
  5. def open_file_write_exclusive(file_name):
  6. """
  7. If file is available - returns file object.
  8. If file is locked - returns None.
  9. If error occured - throws error.
  10. Truncates opened file.
  11. """
  12.  
  13. try:
  14. fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  15.  
  16. except OSError as e:
  17. if e.errno == errno.EEXIST:
  18. fd = os.open(file_name, os.O_WRONLY)
  19. else:
  20. raise
  21.  
  22. fl = os.fdopen(fd, 'w')
  23.  
  24. try:
  25. fcntl.flock(fl, fcntl.LOCK_EX | fcntl.LOCK_NB)
  26.  
  27. except IOError as e:
  28. if e.errno == errno.EAGAIN:
  29. return None
  30. else:
  31. raise
  32.  
  33. fl.truncate(0)
  34.  
  35. return fl
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement