1FILELOCK(1)                        filelock                        FILELOCK(1)
2
3
4

NAME

6       filelock - filelock 3.8.2
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

SIMILAR LIBRARIES

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
32       • the flufl.lock 3rd party library.
33

INSTALLATION

35       filelock is available via PyPI, so you can pip install it:
36
37          python -m pip install filelock
38

TUTORIAL

40       A FileLock is used to indicate another process of your application that
41       a resource or working directory is currently used. To do so,  create  a
42       FileLock first:
43
44          from filelock import Timeout, FileLock
45
46          file_path = "high_ground.txt"
47          lock_path = "high_ground.txt.lock"
48
49          lock = FileLock(lock_path, timeout=1)
50
51       The  lock object supports multiple ways for acquiring the lock, includ‐
52       ing the ones used to acquire standard Python thread locks:
53
54          with lock:
55              with open(file_path, "a") as f:
56                  f.write("Hello there!")
57
58          lock.acquire()
59          try:
60              with open(file_path, "a") as f:
61                  f.write("General Kenobi!")
62          finally:
63              lock.release()
64
65
66          @lock
67          def decorated():
68              print("You're a decorated Jedi!")
69
70
71          decorated()
72
73       The acquire method accepts also a timeout parameter. If the lock cannot
74       be acquired within timeout seconds, a Timeout exception is raised:
75
76          try:
77              with lock.acquire(timeout=10):
78                  with open(file_path, "a") as f:
79                      f.write("I have a bad feeling about this.")
80          except Timeout:
81              print("Another instance of this application currently holds the lock.")
82
83       The  lock  objects are recursive locks, which means that once acquired,
84       they will not block on successive lock requests:
85
86          def cite1():
87              with lock:
88                  with open(file_path, "a") as f:
89                      f.write("I hate it when he does that.")
90
91
92          def cite2():
93              with lock:
94                  with open(file_path, "a") as f:
95                      f.write("You don't want to sell me death sticks.")
96
97
98          # The lock is acquired here.
99          with lock:
100              cite1()
101              cite2()
102          # And released here.
103

LOGGING

105       All log messages by this library are made using the DEBUG_ level, under
106       the filelock name. On how to control displaying/hiding that please con‐
107       sult the logging documentation of the standard library.  E.g.  to  hide
108       these messages you can use:
109
110          logging.getLogger("filelock").setLevel(logging.INFO)
111

FILELOCK VS SOFTFILELOCK

113       The  FileLock  is platform dependent while the SoftFileLock is not. Use
114       the FileLock if all instances of your application are  running  on  the
115       same platform and a SoftFileLock otherwise.
116
117       The  SoftFileLock  only  watches  the  existence of the lock file. This
118       makes it ultra portable, but also more prone to dead locks if  the  ap‐
119       plication crashes. You can simply delete the lock file in such cases.
120

ASYNCIO SUPPORT

122       This  library currently does not support asyncio. We'd recommend adding
123       an asyncio variant though if someone can make a pull  request  for  it,
124       see here.
125

CONTRIBUTIONS AND ISSUES

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

AUTHOR

551       unknown
552
554       2014-2023, tox-dev
555
556
557
558
5593.8                            January 20, 2023                    FILELOCK(1)
Impressum