python使用Mutex保证程序只有一个实例运行,pythonmutex,有时候我们需要程序只运行
python使用Mutex保证程序只有一个实例运行,pythonmutex,有时候我们需要程序只运行
有时候我们需要程序只运行一个实例,在windows平台下我们可以很简单的用mutex实现这个目的。
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)#---------------------------------------------## 用法实例 #from singleinstance import singleinstancefrom sys import exit# 在程序运行之前运行下面代码myapp = singleinstance()# 检查是否已经有实例在运行了if myapp.aleradyrunning(): print "Another instance of this program is already running" exit(0)# 如果没有运行则正常运行程序print "No another instance is running, can continue here"
在开始时,程序创建了一个命名的mutex,这个mutex可以被其他进程检测到。 这样如果程序已经启动,再次运行时的进程就可以检测到程序已运行,从而不会继续运行。
相关内容
- 把用汉字表示的数字转换为阿拉伯数字,汉字阿拉伯
- python 计算时间差,时间运算代码,python时间差,Q:如何方
- python获得汉字拼音的代码,python汉字拼音,#!/usr/bin/e
- 在Python中使用linux的命名管道,pythonlinux,在Python中使用
- 在python中使用json格式文件做配置文件,,json格式小巧玲
- twisted udp 实现示例,twistedudp,from twisted
- webpy更新程序时删除pyc文件的shell脚本,webpypyc,pyc文件是
- Python连接SqlServer代码示例,pythonsqlserver,Python编程语言简
- python 解析xml示例代码,pythonxml示例代码,python有三种方
- 理解python的decorator,pythondecorator,假定有这么一个需求,
评论关闭