A rudimentary file lock class.
| 47 | |
| 48 | |
| 49 | class FileLock: |
| 50 | """A rudimentary file lock class.""" |
| 51 | |
| 52 | def __init__(self, lock_file): |
| 53 | # The path to the lock file. |
| 54 | self.lock_file = lock_file |
| 55 | |
| 56 | # The file descriptor for the lock file |
| 57 | self.lock_file_fd = None |
| 58 | |
| 59 | @property |
| 60 | def is_locked(self): |
| 61 | """This property signals if we are holding the lock.""" |
| 62 | return self.lock_file_fd is not None |
| 63 | |
| 64 | def __enter__(self, poll_intervall=0.01): |
| 65 | |
| 66 | while not self.is_locked: |
| 67 | |
| 68 | if msvcrt: |
| 69 | self.lock_file_fd = acquire_win(self.lock_file) |
| 70 | elif fcntl: |
| 71 | self.lock_file_fd = acquire_nix(self.lock_file) |
| 72 | |
| 73 | time.sleep(poll_intervall) |
| 74 | |
| 75 | return self |
| 76 | |
| 77 | def __exit__(self, exc_type, exc_value, traceback): |
| 78 | |
| 79 | if self.is_locked: |
| 80 | |
| 81 | fd = self.lock_file_fd |
| 82 | self.lock_file_fd = None |
| 83 | |
| 84 | if msvcrt: |
| 85 | msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) |
| 86 | elif fcntl: |
| 87 | fcntl.flock(fd, fcntl.LOCK_UN) |
| 88 | |
| 89 | os.close(fd) |
no outgoing calls