Python只允许同一个py文件执行一个process
在计划任务使用周期性的任务的时候,经常会遇到一个问题py文件同时启动了很多次,造成windows系统中进程很多,并且查看进程名称都是python.exe。以下代码仅限windows
测试在WinXP成功,Other OS 没有测试过。
import os import re import sys
def getProcessInfo(processName): command ="tasklist | findstr \""+processName[0]+"\"" ret = os.system(command) if ret != 0: #can't find it #print processName[0]+" can't find it" return False else: #find it #print processName[0]+" find it" command = 'wmic process where caption="'+processName[0]+'" get caption,commandline /value' pipe = os.popen(command) pipeString = pipe.read() pipe.close() #matchObj = re.compile(r"CommandLine=.+?"+processName[0]+" (.+?)\r\n",re.I) matchObj = re.compile(r"CommandLine=.+?python.exe['\"]{1}[\\t ]*[\"']{1}(.+?)[\"']{1}",re.I) #CommandLine=.+?python.exe['"]{1}[\t ]*["']{1}(.+?)["']{1} list = matchObj.findall(pipeString) number = 0 print pipeString for i in list: print i if i == processName[1]: #print processName[0]+" "+processName[1]+" find it" number=number+1
if number >= 2: return True else: #print processName[1]+" can't find it" return False
def getProcessCount(processName): command ='tasklist | findstr "'+processName[0]+'"'
#print getProcessInfo(["python.exe","-k imgsvc"]) #-k imgsvc if getProcessInfo(["python.exe",sys.argv[0]]) == True: #is process myself print sys.argv[0]+" is alway running!!!" os.system("pause") else: print sys.argv[0]+" isn't running!!!" os.system("pause") |
如果在程序中调用最后几行的函式,就能够很好的解决前面提到的这个问题;发现自己是否还正在运行中。。