python的文件锁操作

相关链接: 

https://cloud.tencent.com/developer/section/1372550

import fcntl
import time
import sys
class TestLock:
    def __init__(self, filename):
        self.filename = filename
        self.fd = open(filename, 'w')

    def acquire(self):
        try:
            fcntl.flock(self.fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
            return True
        except IOError:
            return False

    def release(self):
        fcntl.flock(self.fd, fcntl.LOCK_UN)

    def __del__(self):
        self.fd.close()

lock=TestLock("/var/lock/test.lock")
if not lock.acquire():
    print("process is already running,don't to repeat")
    sys.exit(11)
time.sleep(10)
lock.release()
原文地址:https://www.cnblogs.com/jkklearn/p/13769748.html