凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

python检查程序本身是否已经运行

2019-09-28 python 996
import os
import psutil


class Pid:
    def __init__(self,file="run.pid"):
        self.file = file

    def write(self):
        pid = os.getpid()
        with open(self.file, "w") as f:
            f.write(str(pid))
            return pid

    def read(self):
        if os.path.exists(self.file):
            with open(self.file, "r") as f:
                return f.read()
        else:
            return '0'

    def checkRun(self):
        pid = int(self.read())
        # 通过检查 记录的 pid 是否在 当前运行的pid列表中 来判断是否已经运行了该程序本身
        if pid>0 and pid in psutil.pids():
            return True
        else:
            return False



if __name__ == "__main__":
    pid =Pid()
    pid.write()
    print(pid.read())


文章评论

0条评论