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=masterself.screen_width = self.root.winfo_screenwidth()#獲得屏幕寬度self.screen_height = self.root.winfo_screenheight() #獲得屏幕高度#self.root.resizable(False, False)#讓高寬都固定self.root.update_idletasks()#刷新GUIself.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 desktopself.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()