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()

 

posted on 2020-10-05 12:59  思此狂  阅读(393)  评论(0编辑  收藏  举报

导航