Python
寫的小程式,程式開啟時,如何防止程式再次開啟,二次開始提示“程式已在運行”
import os
import psutil
import time
import sys
if os.path.exists('pid.txt'):
with open('pid.txt','r') as f:
pidread = f.read()
running_pids = psutil.pids()
b = int(pidread)
if b in running_pids:
sys.exit(0)
else:
pid = os.getpid()
with open('pid.txt', 'w') as f:
f.write(str(pid))
f.close()
else:
pid = os.getpid()
with open('pid.txt', 'w') as f:
f.write(str(pid))
f.close()
time.sleep(30)