portalocker.lock(file_, flags)[source]

Lock a file. Note that this is an advisory lock on Linux/Unix systems


Unlock a file

portalocker.LOCK_EX = 2

Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.

portalocker.LOCK_SH = 1

Place a shared lock. More than one process may hold a shared lock for a given file at a given time.

portalocker.LOCK_NB = 4

Acquire the lock in a non-blocking fashion.

portalocker.LOCK_UN = 8

Remove an existing lock held by this process.

exception portalocker.LockException[source]

Bases: portalocker.exceptions.BaseLockException

Exception thrown if an error occurred during locking

class portalocker.Lock(filename, mode='a', timeout=5, check_interval=0.25, fail_when_locked=False, flags=6)[source]

Bases: object

Locking utility class to automatically handle opening with timeouts and context wrappers

acquire(timeout=None, check_interval=None, fail_when_locked=None)[source]

Acquire the locked filehandle


Releases the currently locked file handle

exception portalocker.AlreadyLocked[source]

Bases: portalocker.exceptions.BaseLockException

Exception thrown when the file is already locked by someone else

portalocker.open_atomic(*args, **kwds)[source]

Open a file for atomic writing. Instead of locking this method allows you to write the entire file and move it to the actual location. Note that this makes the assumption that a rename is atomic on your platform which is generally the case but not a guarantee.


>>> filename = 'test_file.txt'
>>> if os.path.exists(filename):
...     os.remove(filename)
>>> with open_atomic(filename) as fh:
...     written = fh.write(b'test')
>>> assert os.path.exists(filename)
>>> os.remove(filename)