是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