Exclusive control with lock file in Python

I wanted to have exclusive control between processes easily with python, so I implemented it with a lock file. The environment we are checking is as follows.

--mac (OS X El Capitan version 10.11.5) --pip available

What to use

A library that creates a lock file with the specified name and performs exclusive control. Since it is managed by pid, when the locked process ends, the exclusive state is released without closing, so it is easy to handle even if an exception occurs. I think. Below, install as usual

$ pip install zc.lockfile

Usage example

There is no particular meaning, but it is implemented with a decorator. It cannot be used when you want to handle the locked process properly (such as outputting a log or waiting). For those who want exclusive control anyway.

lock.py


# -*- coding: utf-8 -*-
import sys
from zc import lockfile
from zc.lockfile import LockError


def lock_or_through(func):
    '''Exclusive control decorator with lock file
Through the process itself if locked
    '''
    def lock(*args, **kwargs):
        lock = None
        try:
            lock = lockfile.LockFile('lock')
        except LockError:
            print("locked")
            return

        func(*args, **kwargs)

        #If the target pid is not valid, it will not be locked, so there is virtually no problem even if an exception occurs.
        lock.close()

    return lock


@lock_or_through
def main(sys_argv):
    """Processing that you want to exclusively control with a lock file"""
    print('process you need')

if __name__ == '__main__':
    main(sys.argv)

Recommended Posts

Exclusive control with lock file in Python
Exclusive file access between processes in Python
File operations in Python
File processing in Python
File operations in Python
Read table data in PDF file with Python
Precautions when dealing with control structures in Python 2.6
Scraping with selenium in Python
Working with LibreOffice in Python
Download the file in Python
Scraping with chromedriver in python
Debugging with pdb in Python
Draw netCDF file with python
Working with sounds in Python
Scraping with Selenium in Python
Scraping with Tor in Python
Tweet with image in Python
Combined with permutations in Python
Run a Python file with relative import in PyCharm
Download csv file with python
Select file in dialog with python → Display file name in message box
Number recognition in images with Python
Extract the xz file with python
Testing with random numbers in Python
File / folder path manipulation in Python
GOTO in Python with Sublime Text 3
Working with LibreOffice in Python: import
[Python] Write to csv file with Python
Save the binary file in Python
[Automation with python! ] Part 1: Setting file
Implemented file download with Python + Bottle
Scraping with Selenium in Python (Basic)
Linebot creation & file sharing in Python
CSS parsing with cssutils in Python
Output to csv file with Python
Numer0n with items made in Python
Open UTF-8 with BOM in Python
Create an Excel file with Python3
Create a binary file in Python
Use rospy with virtualenv in Python3
Use Python in pyenv with NeoVim
Heatmap with Dendrogram in Python + matplotlib
Read files in parallel with Python
Password generation in texto with python
Try frequency control simulation with Python
Use OpenCV with Python 3 in Window
ORC, Parquet file operations in Python
[Automation with python! ] Part 2: File operation
Until dealing with python in Atom
Get started with Python in Blender
Working with DICOM images in Python
Read a file in Python with a relative path from the program
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Creating a simple PowerPoint file with Python
Try logging in to qiita with Python
Stress Test with Locust written in Python
Python3> in keyword> True with partial match?
Device monitoring with On-box Python in IOS-XE
Read CSV file with python (Download & parse CSV file)
Try working with binary data in Python
Check the existence of the file with python