LoginSignup
12
13

More than 5 years have passed since last update.

Pythonでプロセス間の排他ファイルアクセス

Posted at

Pythonでプロセス間の排他ファイル制御をするための方法を調べたのでメモ。
lockfileというものがあるが、そのドキュメントに

This package is deprecated. It is highly preferred that instead of
using this code base that instead fasteners or oslo.concurrency is
used instead.

とあるのでfastenersを使ってみる。
PyPIにあるのでpipで簡単にインストールできる:

pip install fasteners

documentExamplesのうち、今回は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を作っておく必要も無いし便利。

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13