编程语言
首页 > 编程语言> > Python脚本防止重复执行

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,Python,lock,self,filename,重复,__,import
来源: https://www.cnblogs.com/small-wei/p/12487529.html