1.這裡介紹的python的單例模式有兩種方式,一種方式是win32event的CreateMutex來實現,另外就是定義一個全域變數
第一種實現方式可以參考這裡http://code.activestate.com/recipes/474070-creating-a-single-instance-application/
from win32event import CreateMutexfrom win32api import CloseHandle, GetLastErrorfrom winerror import ERROR_ALREADY_EXISTSclass singleinstance: """ Limits application to single instance """ def __init__(self): self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}" self.mutex = CreateMutex(None, False, self.mutexname) self.lasterror = GetLastError() def aleradyrunning(self): return (self.lasterror == ERROR_ALREADY_EXISTS) def __del__(self): if self.mutex: CloseHandle(self.mutex)#---------------------------------------------## sample usage:#from singleinstance import singleinstancefrom sys import exit# do this at beginnig of your applicationmyapp = singleinstance()# check is another instance of same program runningif myapp.aleradyrunning(): print "Another instance of this program is already running" exit(0)# not running, safe to continue...print "No another instance is running, can continue here"## end of http://code.activestate.com/recipes/474070/ }}}
2.對於方法2,網上的方法很多,這裡就簡單的摘抄一個,http://dev.firnow.com/course/1_web/webjs/200855/114357.html
代碼
class Logger(object):
log = None
@staticmethod
def new():
if not Logger.log:
Logger.log = Logger()
return Logger.log
def write(self, v):
print str(self), v
log1 = Logger.new()
log1.write("log1")
log2 = Logger.new()
log2.write("log2")
“”“
分析:很簡單的實現方法,把當前執行個體儲存起來,下次執行個體化時再返回以前的執行個體。但是在判斷的時候保證不了是安全執行緒的。放在這裡,先有個思路。
"""