1FILELOCK(1) filelock FILELOCK(1)
2
3
4
6 filelock - filelock 3.7.1
7
8 This package contains a single module, which implements a platform in‐
9 dependent file lock in Python, which provides a simple way of in‐
10 ter-process communication:
11
12 from filelock import Timeout, FileLock
13
14 lock = FileLock("high_ground.txt.lock")
15 with lock:
16 with open("high_ground.txt", "a") as f:
17 f.write("You were the chosen one.")
18
19 Don't use a FileLock to lock the file you want to write to, instead
20 create a separate .lock file as shown above. [image: Example gif] [im‐
21 age]
22
24 Perhaps you are looking for something like:
25
26 • the pid 3rd party library,
27
28 • for Windows the msvcrt module in the standard library,
29
30 • for UNIX the fcntl module in the standard library.
31
33 filelock is available via PyPI, so you can pip install it:
34
35 python -m pip install filelock
36
38 A FileLock is used to indicate another process of your application that
39 a resource or working directory is currently used. To do so, create a
40 FileLock first:
41
42 from filelock import Timeout, FileLock
43
44 file_path = "high_ground.txt"
45 lock_path = "high_ground.txt.lock"
46
47 lock = FileLock(lock_path, timeout=1)
48
49 The lock object supports multiple ways for acquiring the lock, includ‐
50 ing the ones used to acquire standard Python thread locks:
51
52 with lock:
53 with open(file_path, "a") as f:
54 f.write("Hello there!")
55
56 lock.acquire()
57 try:
58 with open(file_path, "a") as f:
59 f.write("General Kenobi!")
60 finally:
61 lock.release()
62
63
64 @lock
65 def decorated():
66 print("You're a decorated Jedi!")
67
68
69 decorated()
70
71 The acquire method accepts also a timeout parameter. If the lock cannot
72 be acquired within timeout seconds, a Timeout exception is raised:
73
74 try:
75 with lock.acquire(timeout=10):
76 with open(file_path, "a") as f:
77 f.write("I have a bad feeling about this.")
78 except Timeout:
79 print("Another instance of this application currently holds the lock.")
80
81 The lock objects are recursive locks, which means that once acquired,
82 they will not block on successive lock requests:
83
84 def cite1():
85 with lock:
86 with open(file_path, "a") as f:
87 f.write("I hate it when he does that.")
88
89
90 def cite2():
91 with lock:
92 with open(file_path, "a") as f:
93 f.write("You don't want to sell me death sticks.")
94
95
96 # The lock is acquired here.
97 with lock:
98 cite1()
99 cite2()
100 # And released here.
101
103 All log messages by this library are made using the DEBUG_ level, under
104 the filelock name. On how to control displaying/hiding that please con‐
105 sult the logging documentation of the standard library. E.g. to hide
106 these messages you can use:
107
108 logging.getLogger("filelock").setLevel(logging.INFO)
109
111 The FileLock is platform dependent while the SoftFileLock is not. Use
112 the FileLock if all instances of your application are running on the
113 same platform and a SoftFileLock otherwise.
114
115 The SoftFileLock only watches the existence of the lock file. This
116 makes it ultra portable, but also more prone to dead locks if the ap‐
117 plication crashes. You can simply delete the lock file in such cases.
118
120 This library currently does not support asyncio. We'd recommend adding
121 an asyncio variant though if someone can make a pull request for it,
122 see here.
123
125 Contributions are always welcome, please make sure they pass all tests
126 before creating a pull request. This module is hosted on GitHub. If you
127 have any questions or suggestions, don't hesitate to open a new issue
128 😊. There's no bad question, just a missed opportunity to learn more.
129
130 API
131 A platform independent file lock that supports the with-statement.
132
133 filelock.__version__
134 version of the project as a string
135
136 filelock.FileLock
137 alias of UnixFileLock
138
139 class filelock.SoftFileLock(lock_file, timeout=- 1)
140 Bases: BaseFileLock
141
142 Simply watches the existence of the lock file.
143
144 exception filelock.Timeout(lock_file)
145 Bases: TimeoutError
146
147 Raised when the lock could not be acquired in timeout seconds.
148
149 lock_file
150 The path of the file lock.
151
152 class filelock.UnixFileLock(lock_file, timeout=- 1)
153 Bases: BaseFileLock
154
155 Uses the fcntl.flock() to hard lock the lock file on unix sys‐
156 tems.
157
158 class filelock.WindowsFileLock(lock_file, timeout=- 1)
159 Bases: BaseFileLock
160
161 Uses the msvcrt.locking() function to hard lock the lock file on
162 windows systems.
163
164 class filelock.BaseFileLock(lock_file, timeout=- 1)
165 Bases: ABC, ContextDecorator
166
167 Abstract base class for a file lock object.
168
169 property lock_file
170
171 Return type
172 str
173
174 Returns
175 path to the lock file
176
177 property timeout
178
179 Return type
180 float
181
182 Returns
183 the default timeout value
184
185 New in version 2.0.0.
186
187
188 property is_locked
189
190 Return type
191 bool
192
193 Returns
194 A boolean indicating if the lock file is holding
195 the lock currently.
196
197 Changed in version 2.0.0: This was previously a method
198 and is now a property.
199
200
201 acquire(timeout=None, poll_interval=0.05, *, poll_inter‐
202 vall=None, blocking=True)
203 Try to acquire the file lock.
204
205 Parameters
206
207 • timeout (types.UnionType[float, None]) -- maxi‐
208 mum wait time for acquiring the lock, None means
209 use the default timeout is and if timeout < 0,
210 there is no timeout and this method will block
211 until the lock could be acquired
212
213 • poll_interval (float) -- interval of trying to
214 acquire the lock file
215
216 • poll_intervall (types.UnionType[float, None]) --
217 deprecated, kept for backwards compatibility,
218 use poll_interval instead
219
220 • blocking (bool) -- defaults to True. If False,
221 function will return immediately if it cannot
222 obtain a lock on the first attempt. Otherwise
223 this method will block until the timeout expires
224 or the lock is acquired.
225
226 Raises Timeout -- if fails to acquire lock within the
227 timeout period
228
229 Return type
230 filelock._api.AcquireReturnProxy
231
232 Returns
233 a context object that will unlock the file when
234 the context is exited
235
236 # You can use this method in the context manager (recommended)
237 with lock.acquire():
238 pass
239
240 # Or use an equivalent try-finally construct:
241 lock.acquire()
242 try:
243 pass
244 finally:
245 lock.release()
246
247 Changed in version 2.0.0: This method returns now a proxy
248 object instead of self, so that it can be used in a with
249 statement without side effects.
250
251
252 release(force=False)
253 Releases the file lock. Please note, that the lock is
254 only completely released, if the lock counter is 0. Also
255 note, that the lock file itself is not automatically
256 deleted.
257
258 Parameters
259 force (bool) -- If true, the lock counter is ig‐
260 nored and the lock is released in every case/
261
262 Return type
263 None
264
265 class filelock.AcquireReturnProxy(lock)
266 Bases: object
267
268 A context aware object that will release the lock file when ex‐
269 iting.
270
271 License
272 py-filelock is public domain:
273
274 This is free and unencumbered software released into the public domain.
275
276 Anyone is free to copy, modify, publish, use, compile, sell, or
277 distribute this software, either in source code form or as a compiled
278 binary, for any purpose, commercial or non-commercial, and by any
279 means.
280
281 In jurisdictions that recognize copyright laws, the author or authors
282 of this software dedicate any and all copyright interest in the
283 software to the public domain. We make this dedication for the benefit
284 of the public at large and to the detriment of our heirs and
285 successors. We intend this dedication to be an overt act of
286 relinquishment in perpetuity of all present and future rights to this
287 software under copyright law.
288
289 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
290 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
291 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
292 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
293 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
294 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
295 OTHER DEALINGS IN THE SOFTWARE.
296
297 For more information, please refer to <http://unlicense.org>
298
299
300 Changelog
301 v3.6.0 (2022-02-17)
302 • Fix pylint warning "Abstract class WindowsFileLock with abstract
303 methods instantiated" PR #135 - by @vonschultz
304
305 • Fix pylint warning "Abstract class UnixFileLock with abstract methods
306 instantiated" PR #135 - by @vonschultz
307
308 v3.5.1 (2022-02-16)
309 • Use time.monotonic instead of time.time for calculating timeouts.
310
311 v3.5.0 (2022-02-15)
312 • Enable use as context decorator
313
314 v3.4.2 (2021-12-16)
315 • Drop support for python 3.6
316
317 v3.4.1 (2021-12-16)
318 • Add stacklevel to deprecation warnings for argument name change
319
320 v3.4.0 (2021-11-16)
321 • Add correct spelling of poll interval parameter for acquire method,
322 raise deprecation warning when using the misspelled form PR #119 - by
323 @XuehaiPan.
324
325 v3.3.2 (2021-10-29)
326 • Accept path types (like pathlib.Path and pathlib.PurePath) in the
327 constructor for FileLock objects.
328
329 v3.3.1 (2021-10-15)
330 • Add changelog to the documentation PR #108 - by @gaborbernat
331
332 • Leave the log level of the filelock logger as not set (previously was
333 set to warning) PR #108 - by @gaborbernat
334
335 v3.3.0 (2021-10-03)
336 • Drop python 2.7 and 3.5 support, add type hints PR #100 - by
337 @gaborbernat
338
339 • Document asyncio support - by @gaborbernat
340
341 • fix typo PR #98 - by @jugmac00
342
343 v3.2.1 (2021-10-02)
344 • Improve documentation
345
346 • Changed logger name from filelock._api to filelock PR #97 - by
347 @hkennyv
348
349 v3.2.0 (2021-09-30)
350 • Raise when trying to acquire in R/O or missing folder PR #96 - by
351 @gaborbernat
352
353 • Move lock acquire/release log from INFO to DEBUG PR #95 - by
354 @gaborbernat
355
356 • Fix spelling and remove ignored flake8 checks - by @gaborbernat
357
358 • Split main module PR #94 - by @gaborbernat
359
360 • Move test suite to pytest PR #93 - by @gaborbernat
361
362 v3.1.0 (2021-09-27)
363 • Update links for new home at tox-dev PR #88 - by @hugovk
364
365 • Fixed link to LICENSE file PR #63 - by @sharkwouter
366
367 • Adopt tox-dev organization best practices PR #87 - by @gaborbernat
368
369 • Ownership moved from @benediktschmitt to the tox-dev organization
370 (new primary maintainer @gaborbernat)
371
372 v3.0.12 (2019-05-18)
373 • fixed setuptools and twine/warehouse error by making the license only
374 1 line long
375
376 • update version for pypi upload
377
378 • fixed python2 setup error
379
380 • added test.py module to MANIFEST and made tests available in the
381 setup commands issue #48
382
383 • fixed documentation thanks to @AnkurTank issue #49
384
385 • Update Trove classifiers for PyPI
386
387 • test: Skip test_del on PyPy since it hangs
388
389 v3.0.10 (2018-11-01)
390 • Fix README rendering on PyPI
391
392 v3.0.9 (2018-10-02)
393 • PR #38 from cottsay/shebang
394
395 • updated docs config for older sphinx compatibility
396
397 • removed misleading shebang from module
398
399 v3.0.8 (2018-09-09)
400 • updated use setuptools
401
402 v3.0.7 (2018-09-09)
403 • fixed garbage collection (issue #37)
404
405 • fix travis ci badge (use rst not markdown)
406
407 • changed travis uri
408
409 v3.0.6 (2018-08-22)
410 • clean up
411
412 • Fixed unit test for Python 2.7
413
414 • Added Travis banner
415
416 • Added Travis CI support
417
418 v3.0.5 (2018-04-26)
419 • Corrected the prequel reference
420
421 v3.0.4 (2018-02-01)
422 • updated README
423
424 v3.0.3 (2018-01-30)
425 • updated readme
426
427 v3.0.1 (2018-01-30)
428 • updated README (added navigation)
429
430 • updated documentation issue #22
431
432 • fix the SoftFileLock test was influenced by the test for FileLock
433
434 • undo cb1d83d issue #31
435
436 v3.0.0 (2018-01-05)
437 • updated major version number due to issue #29 and issue #27
438
439 • fixed use proper Python3 reraise method
440
441 • Attempting to clean up lock file on Unix after release
442
443 v2.0.13 (2017-11-05)
444 • changed The logger is now acquired when first needed. issue #24
445
446 v2.0.12 (2017-09-02)
447 • correct spelling mistake
448
449 v2.0.11 (2017-07-19)
450 • added official support for python 2 issue #20
451
452 v2.0.10 (2017-06-07)
453 • updated readme
454
455 v2.0.9 (2017-06-07)
456 • updated readme issue #19
457
458 • added example PR #16
459
460 • updated readthedocs url
461
462 • updated change order of the examples (PR #16)
463
464 v2.0.8 (2017-01-24)
465 • Added logging
466
467 • Removed unused imports
468
469 v2.0.7 (2016-11-05)
470 • fixed issue #14 (moved license and readme file to MANIFEST)
471
472 v2.0.6 (2016-05-01)
473 • changed unlocking sequence to fix transient test failures
474
475 • changed threads in tests so exceptions surface
476
477 • added test lock file cleanup
478
479 v2.0.5 (2015-11-11)
480 • Don't remove file after releasing lock
481
482 • updated docs
483
484 v2.0.4 (2015-07-29)
485 • added the new classes to __all__
486
487 v2.0.3 (2015-07-29)
488 • added The SoftFileLock is now always tested
489
490 v2.0.2 (2015-07-29)
491 • The filelock classes are now always available and have been moved out
492 of the if msvrct: ... elif fcntl ... else clauses.
493
494 v2.0.1 (2015-06-13)
495 • fixed issue #5
496
497 • updated test cases
498
499 • updated documentation
500
501 • fixed issue #2 which has been introduced with the lock counter
502
503 v2.0.0 (2015-05-25)
504 • added default timeout (fixes issue #2)
505
506 v1.0.3 (2015-04-22)
507 • added new test case, fixed unhandled exception
508
509 v1.0.2 (2015-04-22)
510 • fixed a timeout could still be thrown if the lock is already acquired
511
512 v1.0.1 (2015-04-22)
513 • fixed issue #1
514
515 v1.0.0 (2015-04-07)
516 • added lock counter, added unittest, updated to version 1
517
518 • changed filenames
519
520 • updated version for pypi
521
522 • updated README, LICENSE (changed format from md to rst)
523
524 • added MANIFEST to gitignore
525
526 • added os independent file lock ; changed setup.py for pypi
527
528 • Update README.md
529
530 • initial version
531
533 unknown
534
536 2014-2022, tox-dev
537
538
539
540
5413.7 August 07, 2022 FILELOCK(1)