Python Singleton Mode

Source: Internet
Author: User

1. the python Singleton mode is described here in two ways. One is implemented by createmutex of win32event, and the other is to define a global variable.

The first implementation method can refer to here 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) # examples # 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. For method 2, a lot of online methods, here is a simple excerpt, http://dev.firnow.com/course/1_web/webjs/200855/114357.html

 

Code

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

"
Analysis: A simple implementation method is to save the current instance and return the previous instance at the next instantiation. However, thread security cannot be ensured during judgment. Put it here, first of all, there is a train of thought.
"""

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.