Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update index.rst to improve the demo usage #314

Merged
merged 1 commit into from
Mar 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ working directory is currently used. To do so, create a :class:`FileLock <filelo

.. code-block:: python

import os
from filelock import Timeout, FileLock

file_path = "high_ground.txt"
Expand All @@ -62,16 +63,19 @@ locks:
.. code-block:: python

with lock:
with open(file_path, "a") as f:
f.write("Hello there!")
if not os.path.exists(file_path):
with open(file_path, "w") as f:
f.write("Hello there!")
# here, all processes can see consistent content in the file

lock.acquire()
try:
with open(file_path, "a") as f:
f.write("General Kenobi!")
if not os.path.exists(file_path):
with open(file_path, "w") as f:
f.write("General Kenobi!")
finally:
lock.release()

# here, all processes can see consistent content in the file

@lock
def decorated():
Expand All @@ -80,6 +84,11 @@ locks:

decorated()

Note: When a process gets the lock (i.e. within the `with lock:` region), it is usually good to check what has
already been done by other processes. For example, each process above first check the existence of the file. If
it is already created, we should not destroy the work of other processes. This is typically the case when we want
just one process to write content into a file, and let every process to read the content.

The :meth:`acquire <filelock.BaseFileLock.acquire>` method accepts also a ``timeout`` parameter. If the lock cannot be
acquired within ``timeout`` seconds, a :class:`Timeout <filelock.Timeout>` exception is raised:

Expand Down
Loading