Python程序互斥体

Python程序互斥体

  有时候我们需要程序只运行一个实例,在windows平台下我们可以很简单的用mutex实现这个目的。
  在开始时,程序创建了一个命名的mutex,这个mutex可以被其他进程检测到。 这样如果程序已经启动,再次运行时的进程就可以检测到程序已运行,从而不会继续运行。

from tkinter import *
import win32event, pywintypes, win32api
from winerror import ERROR_ALREADY_EXISTS
class MyFrm(Frame):
    def __init__(self, master):
        self.root=master
        self.screen_width = self.root.winfo_screenwidth()#获得屏幕宽度
        self.screen_height = self.root.winfo_screenheight()  #获得屏幕高度
        #self.root.resizable(False, False)#让高宽都固定
        self.root.update_idletasks()#刷新GUI
        self.root.withdraw() #暂时不显示窗口来移动位置
        self.root.geometry('%dx%d+%d+%d' % (self.root.winfo_width(), self.root.winfo_height() ,(self.screen_width - self.root.winfo_width()) / 2,(self.screen_height - self.root.winfo_height()) / 2))  # center window on desktop
        self.root.deiconify()
        Label(self.root,text='程序运行中...').pack(fill=BOTH,expand=YES)

if __name__=='__main__':
    mutexname = "DEMO"#互斥体命名
    mutex = win32event.CreateMutex(None, FALSE, mutexname)
    if (win32api.GetLastError() == ERROR_ALREADY_EXISTS):
        print('程序已启动')
        exit(0)
    root=Tk()
    MyFrm(root)
    root.mainloop()

转载于:https://www.cnblogs.com/d0main/p/7613302.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值