最近开始学习Python,碰上定时计划任务因为网络延迟等原因导致会重复执行,原理是通过pgrep命令获取同文件名的进程PID并获取数量,超过1个则exit。
windows修改类似命令也可以 cmd /c tasklist |find “*”
def disableSec(): proc = subprocess.Popen(["pgrep", "-f", os.path.basename(__file__)], stdout=subprocess.PIPE) std = proc.communicate() print(std[0].decode()) if len(std[0].decode().split()) > 1: exit('Already running')
注意:py文件名需要独特一点。