Developer 2024 🎇限时优惠进行中,现在购买立即享受

现在购买

Python 寫的小程式,程式開啟時,如何防止程式再次開啟,二次開始提示“程式已在運行”

avatar用户_62OH7Lya
2月21日936次阅读

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)
发布评论
登录后发表内容
2个评论