@@ -49,6 +49,7 @@ working directory is currently used. To do so, create a :class:`FileLock <filelo
49
49
50
50
.. code-block :: python
51
51
52
+ import os
52
53
from filelock import Timeout, FileLock
53
54
54
55
file_path = " high_ground.txt"
@@ -62,16 +63,19 @@ locks:
62
63
.. code-block :: python
63
64
64
65
with lock:
65
- with open (file_path, " a" ) as f:
66
- f.write(" Hello there!" )
66
+ if not os.path.exists(file_path):
67
+ with open (file_path, " w" ) as f:
68
+ f.write(" Hello there!" )
69
+ # here, all processes can see consistent content in the file
67
70
68
71
lock.acquire()
69
72
try :
70
- with open (file_path, " a" ) as f:
71
- f.write(" General Kenobi!" )
73
+ if not os.path.exists(file_path):
74
+ with open (file_path, " w" ) as f:
75
+ f.write(" General Kenobi!" )
72
76
finally :
73
77
lock.release()
74
-
78
+ # here, all processes can see consistent content in the file
75
79
76
80
@lock
77
81
def decorated ():
@@ -80,6 +84,11 @@ locks:
80
84
81
85
decorated()
82
86
87
+ Note: When a process gets the lock (i.e. within the `with lock: ` region), it is usually good to check what has
88
+ already been done by other processes. For example, each process above first check the existence of the file. If
89
+ it is already created, we should not destroy the work of other processes. This is typically the case when we want
90
+ just one process to write content into a file, and let every process to read the content.
91
+
83
92
The :meth: `acquire <filelock.BaseFileLock.acquire> ` method accepts also a ``timeout `` parameter. If the lock cannot be
84
93
acquired within ``timeout `` seconds, a :class: `Timeout <filelock.Timeout> ` exception is raised:
85
94
0 commit comments