An easy library for Python file locking. It works on Windows, Linux, BSD and Unix systems and can even perform distributed locking. Naturally it also supports the with statement.
See the codePortalocker provides file locks for Python on Linux, macOS and Windows. Use a context manager to coordinate access between processes, a semaphore to limit concurrent workers, or a Redis lock to coordinate across machines. Python 3.10 or later is required.
Get started | Choose a lock | API reference | Changelog
python -m pip install portalocker
Exclusive file locks work without extra dependencies. Install the optional
redis extra for Redis locks, or win32 for shared file locks on Windows:
python -m pip install "portalocker[redis]"
python -m pip install "portalocker[win32]"
Redis locks need a Redis server. Shared file locks on Windows without pywin32
raise an ImportError explaining which extra to install.
Use the file handle inside the context:
import portalocker
with portalocker.Lock('report.txt', 'a', timeout=5) as fh:
fh.write('Report complete.\n')
Lock waits up to five seconds to acquire the lock. Leaving the context
releases the lock and closes the file, including when the body raises an
exception. Give every participating process the same file path.
When another holder prevents acquisition, AlreadyLocked lets you handle
contention separately from other failures:
import portalocker
with portalocker.Lock('worker.lock', 'a', timeout=1):
try:
with portalocker.Lock('worker.lock', 'a', timeout=0):
print('The second holder entered.')
except portalocker.AlreadyLocked:
print('The first holder still owns the lock.')
with portalocker.Lock('worker.lock', 'a', timeout=0):
print('The lock is available after release.')
The second lock cannot enter while the first is held. Once the outer context exits, a new holder can acquire it. This example uses the default file-locking backend. See platform behaviour before choosing a different POSIX locking primitive.
| Your task | Lock | Guide |
|---|---|---|
| Coordinate access to a file | Lock | File locking |
| Acquire again through the same lock instance | RLock | Reentrant locks |
| Limit the number of concurrent workers | NamedBoundedSemaphore | Workers and slots |
| Inspect a worker PID or run a singleton | PidFileLock | PID files |
| Coordinate processes across machines | RedisLock | Redis locks |
Give cooperating semaphores the same explicit name and directory. Keep
their slot files in a directory that will survive while workers hold them.
fh.flush() followed by os.fsync(fh.fileno()) before releasing a lock.
Read the platform guide
and test on the filesystem you deploy to.PidFileLock context is for inspection by default. Its body runs even
when another process holds the lock, returning that holder's PID. None
means this process acquired it. An unreadable or corrupt PID for a held
lock raises AlreadyLocked. Use fail_closed() when the body must only
run after acquisition. See the PID examples.lost, ensure_held(), health checks and optional fencing tokens.
Fencing only protects writes when the resource checks the token.For single-file vendoring, see the CLI guide. For upgrades from 3.x, see the migration guide.
Portalocker is maintained by Rick van Hattem. Bug reports and feature requests and patches are welcome. See the contribution guide for development and test commands.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
portalocker is maintained by Rick van Hattem in his own time. Most of that time goes on the platforms you are not running, so the lock behaves the same on Windows, BSD and NFS as it does on your laptop.
If it saved you an afternoon, a tip covers an hour of issue triage: Ko-fi or GitHub Sponsors.
If your company funds its dependencies, this package is on thanks.dev.
Portalocker is distributed under the BSD 3-Clause licence. See LICENSE.
350 followers · starred Jul 2022
29 followers · starred Sep 2023
67 followers · starred Dec 2024
An easy library for Python file locking. It works on Windows, Linux, BSD and Unix systems and can even perform distributed locking. Naturally it also supports the with statement.
See the codePortalocker provides file locks for Python on Linux, macOS and Windows. Use a context manager to coordinate access between processes, a semaphore to limit concurrent workers, or a Redis lock to coordinate across machines. Python 3.10 or later is required.
Get started | Choose a lock | API reference | Changelog
python -m pip install portalocker
Exclusive file locks work without extra dependencies. Install the optional
redis extra for Redis locks, or win32 for shared file locks on Windows:
python -m pip install "portalocker[redis]"
python -m pip install "portalocker[win32]"
Redis locks need a Redis server. Shared file locks on Windows without pywin32
raise an ImportError explaining which extra to install.
Use the file handle inside the context:
import portalocker
with portalocker.Lock('report.txt', 'a', timeout=5) as fh:
fh.write('Report complete.\n')
Lock waits up to five seconds to acquire the lock. Leaving the context
releases the lock and closes the file, including when the body raises an
exception. Give every participating process the same file path.
When another holder prevents acquisition, AlreadyLocked lets you handle
contention separately from other failures:
import portalocker
with portalocker.Lock('worker.lock', 'a', timeout=1):
try:
with portalocker.Lock('worker.lock', 'a', timeout=0):
print('The second holder entered.')
except portalocker.AlreadyLocked:
print('The first holder still owns the lock.')
with portalocker.Lock('worker.lock', 'a', timeout=0):
print('The lock is available after release.')
The second lock cannot enter while the first is held. Once the outer context exits, a new holder can acquire it. This example uses the default file-locking backend. See platform behaviour before choosing a different POSIX locking primitive.
| Your task | Lock | Guide |
|---|---|---|
| Coordinate access to a file | Lock | File locking |
| Acquire again through the same lock instance | RLock | Reentrant locks |
| Limit the number of concurrent workers | NamedBoundedSemaphore | Workers and slots |
| Inspect a worker PID or run a singleton | PidFileLock | PID files |
| Coordinate processes across machines | RedisLock | Redis locks |
Give cooperating semaphores the same explicit name and directory. Keep
their slot files in a directory that will survive while workers hold them.
fh.flush() followed by os.fsync(fh.fileno()) before releasing a lock.
Read the platform guide
and test on the filesystem you deploy to.PidFileLock context is for inspection by default. Its body runs even
when another process holds the lock, returning that holder's PID. None
means this process acquired it. An unreadable or corrupt PID for a held
lock raises AlreadyLocked. Use fail_closed() when the body must only
run after acquisition. See the PID examples.lost, ensure_held(), health checks and optional fencing tokens.
Fencing only protects writes when the resource checks the token.For single-file vendoring, see the CLI guide. For upgrades from 3.x, see the migration guide.
Portalocker is maintained by Rick van Hattem. Bug reports and feature requests and patches are welcome. See the contribution guide for development and test commands.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
portalocker is maintained by Rick van Hattem in his own time. Most of that time goes on the platforms you are not running, so the lock behaves the same on Windows, BSD and NFS as it does on your laptop.
If it saved you an afternoon, a tip covers an hour of issue triage: Ko-fi or GitHub Sponsors.
If your company funds its dependencies, this package is on thanks.dev.
Portalocker is distributed under the BSD 3-Clause licence. See LICENSE.
350 followers · starred Jul 2022
29 followers · starred Sep 2023
67 followers · starred Dec 2024