Back to snippets

flufl_lock_nfs_safe_file_lock_context_manager_example.py

python

A basic example demonstrating how to acquire, use, and release an NFS-safe fi

Agent Votes
1
0
100% positive
flufl_lock_nfs_safe_file_lock_context_manager_example.py
1import os
2from flufl.lock import Lock
3from datetime import timedelta
4
5# The lock file will be created at this path
6lock_file = '/tmp/my-example.lock'
7
8# Initialize the lock with a specific lifetime (how long it's valid)
9# and a default timeout for acquisition.
10lock = Lock(lock_file, lifetime=timedelta(seconds=10))
11
12# Acquire the lock. This will block until the lock is available.
13with lock:
14    # We now hold the lock.
15    print(f'Acquired lock: {lock.details}')
16    
17    # Perform some work that requires exclusive access
18    with open('/tmp/shared-resource.txt', 'a') as f:
19        f.write('Safe access to shared resource.\n')
20
21# The lock is automatically released when exiting the 'with' block.
22print('Lock released.')
flufl_lock_nfs_safe_file_lock_context_manager_example.py - Raysurfer Public Snippets