Simple file locking for Windows using msvcrt
| 89 | import os |
| 90 | |
| 91 | class WindowsFileLock(BaseLock): |
| 92 | """Simple file locking for Windows using msvcrt""" |
| 93 | |
| 94 | def __init__(self, filename: str) -> None: |
| 95 | super().__init__() |
| 96 | self.filename = f"{filename}.lock" |
| 97 | self.fileobj = -1 |
| 98 | |
| 99 | def acquire(self) -> None: |
| 100 | # create a lock file and lock it |
| 101 | self.fileobj = os.open( |
| 102 | self.filename, os.O_RDWR | os.O_CREAT | os.O_TRUNC |
| 103 | ) |
| 104 | msvcrt.locking(self.fileobj, msvcrt.LK_NBLCK, 1) |
| 105 | |
| 106 | self.locked = True |
| 107 | |
| 108 | def release(self) -> None: |
| 109 | self.locked = False |
| 110 | |
| 111 | # unlock lock file and remove it |
| 112 | msvcrt.locking(self.fileobj, msvcrt.LK_UNLCK, 1) |
| 113 | os.close(self.fileobj) |
| 114 | self.fileobj = -1 |
| 115 | |
| 116 | try: |
| 117 | os.remove(self.filename) |
| 118 | except OSError: |
| 119 | pass |
| 120 | |
| 121 | has_msvcrt = True |
| 122 | except ImportError: |