LoginSignup
2
1

More than 3 years have passed since last update.

pythonで多重起動禁止

Posted at

fcntl --- fcntl および ioctl システムコール — Python 3.9.1 ドキュメント

lock_test.py
import os
import fcntl
import time

def process_lock():
    lockfile = os.path.splitext(os.path.abspath(__file__))[0] + '.lock'
    lockfp = open(lockfile, "w")
    try:
        fcntl.flock(lockfp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return
    return lockfp

def main():
    lock = process_lock()
    if not lock:
        print("lock error")
        exit(1)

    # 処理
    time.sleep(360)

if __name__ == '__main__':
    main()
$ python3 lock_test.py &
$ python3 lock_test.py
lock error
2
1
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
2
1