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
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
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