Note that I investigated how to control exclusive files between processes in Python. There is a lockfile in the documentation
This package is deprecated. It is highly preferred that instead of using this code base that instead
fasteners
oroslo.concurrency
is used instead.
Since there is, try using fasteners.
It's located at PyPI so it's easy to install with pip
:
pip install fasteners
Of the Examples in the document, this time interprocess lock Try using it.
You can use with
or make it a decorator.
import os
import time
import fasteners
def main():
pid = os.getpid()
while True:
print("Waiting...")
with fasteners.InterProcessLock('/tmp/tmp_lock_file'):
print('Locked by {}'.format(pid))
time.sleep(2)
time.sleep(1)
if __name__ == '__main__':
main()
The part inside with
is executed exclusively.
import os
import time
import fasteners
@fasteners.interprocess_locked("/tmp/tmp_lock_file")
def action_with_lock():
pid = os.getpid()
print("{} has a lock".format(pid))
time.sleep(1)
if __name__ == '__main__':
action_with_lock()
If you want to execute one function exclusively, here.
Both are easy to implement.
It is convenient because it is not necessary to create / tmp / tmp_lock_file
in advance.
Recommended Posts