wxPython怎么控制只能运行一个实例程序?

写了一个wxPython的图像化小程序,在ide上运行的时候没问题。但是每次点击一次ide的运行按钮,都会再次运行一个程序。。。
怎么样做?判断一下如果已经运行了就把当前运行的显示出来就可以了,类似于单例这样,还望各位兄弟姐妹指导一下!!!

阅读 4.3k
2 个回答

是windows还是Linux平台,linux平台一般是写一个文件比如myps.pid,然后把自己的pid写进去,每次启动的时候读这个固定的文件,然后监测下有无对应的pid进程在,有的话,主动退出。你可以把这个pid写到/tmp目录下
windows可以用核心对象来判断,这个有代码支持的,自己简单写了下windows的测试代码,linux可以自行加上

# -*- coding: utf-8 -*-

import sys
import time
if sys.platform.startswith("win32"):
    from win32api import GetLastError
    from winerror import ERROR_ALREADY_EXISTS

ORG = "MyCompany"
APP_NAME = "MyAppName"


class Singleton(object):
    def __init__(self):
        if sys.platform.startswith("win32"):
            from win32event import CreateMutex
            self.mutexName = '%s.%s' % (ORG, APP_NAME)
            self.myMutex = CreateMutex(None, False, self.mutexName) //创建核心对象
            self.lastErr = GetLastError() //检查lasterr
        else:
            # 是linux平台,可以把文件固定写在/tmp下,每次读这个文件检查pid内容,看是否有同样的pid存在
            pass

    def isAlive(self):
        if sys.platform.startswith("win32"):
            if self.lastErr == ERROR_ALREADY_EXISTS: //如果LastError表示已经存在,则返回,表示进程表里有同样的进程存在
                return True
        else:
            # 检查
            return False

参见官方示例:

#!/usr/bin/python
# coding: utf-8
def OnInit(self):

    # Give a name to the wx.App
    name = "MyApp-%s"%wx.GetUserId()

    self._checker = wx.SingleInstanceChecker(name)
    if self._checker.IsAnotherRunning():
        raise Exception("Another program instance is already running, aborting.")
        return False        # 如果打包之后报错,尝试 return True

    # ... more initializations here ...

    return True


def OnExit(self):

    del self._checker
    return 0

wx.SingleInstanceChecker

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题