Pythonでプロセス間の排他ファイル制御をするための方法を調べたのでメモ。
lockfileというものがあるが、そのドキュメントに
This package is deprecated. It is highly preferred that instead of
using this code base that insteadfasteners
oroslo.concurrency
is
used instead.
とあるのでfastenersを使ってみる。
PyPIにあるのでpip
で簡単にインストールできる:
pip install fasteners
documentのExamplesのうち、今回はinterprocess lockを使ってみる。
with
を使う方法とデコレータにする方法がある。
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()
with
の中の部分が排他的に実行される。
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()
一つの関数を排他的に実行したい場合はこっち。
いずれも簡単に実装できる。
予め/tmp/tmp_lock_file
を作っておく必要も無いし便利。