• Stars
    star
    226
  • Rank 176,514 (Top 4 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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.

portalocker - Cross-platform locking library

Linux Test Status Windows Tests Status Coverage Status

Overview

Portalocker is a library to provide an easy API to file locking.

An important detail to note is that on Linux and Unix systems the locks are advisory by default. By specifying the -o mand option to the mount command it is possible to enable mandatory file locking on Linux. This is generally not recommended however. For more information about the subject:

The module is currently maintained by Rick van Hattem <[email protected]>. The project resides at https://github.com/WoLpH/portalocker . Bugs and feature requests can be submitted there. Patches are also very welcome.

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Redis Locks

This library now features a lock based on Redis which allows for locks across multiple threads, processes and even distributed locks across multiple computers.

It is an extremely reliable Redis lock that is based on pubsub.

As opposed to most Redis locking systems based on key/value pairs, this locking method is based on the pubsub system. The big advantage is that if the connection gets killed due to network issues, crashing processes or otherwise, it will still immediately unlock instead of waiting for a lock timeout.

First make sure you have everything installed correctly:

pip install "portalocker[redis]"

Usage is really easy:

import portalocker

lock = portalocker.RedisLock('some_lock_channel_name')

with lock:
    print('do something here')

The API is essentially identical to the other Lock classes so in addition to the with statement you can also use lock.acquire(...).

Python 2

Python 2 was supported in versions before Portalocker 2.0. If you are still using Python 2, you can run this to install:

pip install "portalocker<2"

Tips

On some networked filesystems it might be needed to force a os.fsync() before closing the file so it's actually written before another client reads the file. Effectively this comes down to:

with portalocker.Lock('some_file', 'rb+', timeout=60) as fh:
    # do what you need to do
    ...

    # flush and sync to filesystem
    fh.flush()
    os.fsync(fh.fileno())

Links

Examples

To make sure your cache generation scripts don't race, use the Lock class:

>>> import portalocker
>>> with portalocker.Lock('somefile', timeout=1) as fh:
...     print('writing some stuff to my cache...', file=fh)

To customize the opening and locking a manual approach is also possible:

>>> import portalocker
>>> file = open('somefile', 'r+')
>>> portalocker.lock(file, portalocker.LockFlags.EXCLUSIVE)
>>> file.seek(12)
>>> file.write('foo')
>>> file.close()

Explicitly unlocking is not needed in most cases but omitting it has been known to cause issues: AzureAD/microsoft-authentication-extensions-for-python#42 (comment)

If needed, it can be done through:

>>> portalocker.unlock(file)

Do note that your data might still be in a buffer so it is possible that your data is not available until you flush() or close().

To create a cross platform bounded semaphore across multiple processes you can use the BoundedSemaphore class which functions somewhat similar to threading.BoundedSemaphore:

>>> import portalocker
>>> n = 2
>>> timeout = 0.1
>>> semaphore_a = portalocker.BoundedSemaphore(n, timeout=timeout)
>>> semaphore_b = portalocker.BoundedSemaphore(n, timeout=timeout)
>>> semaphore_c = portalocker.BoundedSemaphore(n, timeout=timeout)
>>> semaphore_a.acquire()
<portalocker.utils.Lock object at ...>
>>> semaphore_b.acquire()
<portalocker.utils.Lock object at ...>
>>> semaphore_c.acquire()
Traceback (most recent call last):
  ...
portalocker.exceptions.AlreadyLocked

More examples can be found in the tests.

Versioning

This library follows Semantic Versioning.

Changelog

Every release has a git tag with a commit message for the tag explaining what was added and/or changed. The list of tags/releases including the commit messages can be found here: https://github.com/WoLpH/portalocker/releases

License

See the LICENSE file.

More Repositories

1

python-progressbar

Progressbar 2 - A progress bar for Python 2 and Python 3 - "pip install progressbar2"
Python
826
star
2

numpy-stl

Simple library to make working with STL files (and 3D objects in general) fast and easy.
Python
607
star
3

python-statsd

Python Client for the Etsy NodeJS Statsd Server
Python
106
star
4

alfred-converter

Alfred unit converter is a smart calculator for Alfred with support for unit conversions to make it a bit comparable to the Google Calculator and Wolfram Alpha.
Python
87
star
5

django-admin-generator

The Django Admin Generator automatically generates (scaffolds) a fully functioning Django admin by introspecting and querying your models
Python
86
star
6

mt940

A library to parse MT940 files and returns smart Python collections for statistics and manipulation.
Python
81
star
7

python-utils

Python Utils is a module with some convenient utilities not included with the standard Python install
Python
80
star
8

django-tags-input

django-tags-input
Python
67
star
9

django-statsd

Django Statsd library to track the page load times with Graphite
Python
63
star
10

pg_query_analyser

A PostgreSQL query analyzer written in C++. Mimicks the output of PgFouine but _much_ faster.
C++
54
star
11

django-utils

Django Utils is a collection of small Django helper functions and classes which make common patterns shorter and easier.
Python
31
star
12

mailjet

Mailjet API implementation in Python
Python
19
star
13

tissue

Tissue - automated pep8 checker for nose
Python
16
star
14

pyExcelerator

pyExcelerator fork with docs
Python
15
star
15

Cache-Debug-Toolbar

Django Cache Debug Toolbar for Redis, Memcache and PyLibMC
Python
13
star
16

python-formatter

A Python formatter based on the Python tokenize lib to ensure validity
Python
11
star
17

django-redis-admin

A Django Admin interface for Redis servers with optional Redis Sentinel support
Python
8
star
18

dotfiles

Wolph's dotfiles, in case you need tmux, zsh or vim example configurations
Shell
6
star
19

splitwise

Small implementation of the Splitwise API using Flask for importing transactions
JavaScript
5
star
20

python-project-tools

Python Project Tools is a package that makes developing and deploying proper Python packages easier
Python
5
star
21

zfs-utils-osx

A simple script to create and manage virtual ZFS images on OS X without requiring repartitioning
Python
5
star
22

dropbox-time-machine

An app that adds a time machine feature to Dropbox, instead of restoring per file you can simply jump back in time (before some idiot deleted all files for example).
Python
5
star
23

wollen-socks

Simple OpenVPN client Socks proxy server combination which supports both Surfshark and NordVPN currently
Shell
4
star
24

Mercury

Django SSI / ESI framework using NGINX and Memcached for static caching with user differentiated content
3
star
25

django-minify

Python
3
star
26

speedups

Python
3
star
27

django-tagging

A generic tagging application for Django projects, which allows association of a number of tags with any Model instance and makes retrieval of tags simple.
Python
3
star
28

trellozilla

Python
2
star
29

eventghost-domoticz

Domoticz plugin for EventGhost
Python
2
star
30

django-inlinetrans

Django Inlinetrans fork with Jinja, Transifex and Babel support
Python
2
star
31

github_difftools

A Chrome Extension to add diff checkboxes buttons to Github :)
JavaScript
2
star
32

sphinx-pypi-upload

This package contains a `setuptools`_ command for uploading `Sphinx`_ documentation to the `Python Package Index`_ (PyPI) at the dedicated URL packages.python.org.
Python
2
star
33

genetic_algorithm

A genetic algorithm implementation in Python for the Traveling Salesman Problem
Python
1
star
34

atmoorb-photon

AtmoOrb Particle Photon code
C++
1
star
35

launchy-ec2

EC2 Plugin for Launchy
Python
1
star
36

universal-syntax-highlighter

This userscript automatically adds syntax highlighting to a large amount of filetypes and in case of JSON also indents.
1
star
37

silk

Django Fabric Project to create a simple webinterface to deploy from Github/Bitbucket. NOTE, this project is currently a stub!
Python
1
star
38

silkproject

Python
1
star
39

supervisord-slack-notifier

Supervisord Slack Event Notifier
Python
1
star
40

dropbox

A fork of the official Dropbox API for better documentation
Python
1
star
41

learnvimscriptthehardway

HTML
1
star
42

Jukify

Webbased Spotify Jukebox written in Python
JavaScript
1
star
43

fping-exporter

Prometheus Exporter for fping
Python
1
star
44

xmlwriter

Python XML writer class inspired by the C# XmlWriter and the Django ORM
Python
1
star
45

tribler

Tribler is an open source peer-to-peer client with various features for watching videos online.
Python
1
star
46

userscript-disable-google-autocorrect

Redirects to "Did you mean" version of Google search instead of automatically correcting you.
JavaScript
1
star