Python脚本防止重复执行

# coding: utf-8

import os
import sys
import time
import fcntl

class Lock:
    def __init__(self, filename):
        self.filename = filename
        # This will create it if does not exist already
        self.handle = open(filename, 'w')

    # Bitwise Or fcntl.LOCK_NB  if you need a non-blocking lock
    def acquire(self):
        fcntl.flock(self.handle, fcntl.LOCK_EX | fcntl.LOCK_EX_NB)
    
    def __del__(self):
        self.handle.close()

lock = Lock(os.path.join('/','tmp',os.path.basename(sys.argv[0]) + '_tmp'))

try:
    lock.acquire()
except:
    print "%s [ERROR] There is already another process running!"
    sys.exit(1)

 

上一篇:fcntl文件加锁


下一篇:fcntl()函数用法