python的单例模式

1.这里介绍的python的单例模式有两种方式,一种方式是win32event的CreateMutex来实现,另外就是定义一个全局变量

第一种实现方式可以参考这里http://code.activestate.com/recipes/474070-creating-a-single-instance-application/

from win32event import CreateMutex

from win32api import CloseHandle, GetLastError

from winerror import ERROR_ALREADY_EXISTS



class 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 singleinstance

from sys import exit



# do this at beginnig of your application

myapp = singleinstance()



# check is another instance of same program running

if 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 " )

“”“
分析:很简单的实现方法,把当前实例保存起来,下次实例化时再返回以前的实例。但是在判断的时候保证不了是线程安全的。放在这里,先有个思路。
"""

 

你可能感兴趣的:(python)