zoukankan      html  css  js  c++  java
  • 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")

    如果在程序中调用最后几行的函式,就能够很好的解决前面提到的这个问题;发现自己是否还正在运行中。。

  • 相关阅读:
    Postman之token动态获取
    AJAX省市县三级联动的实现
    Javamail简单使用案例
    JavaWeb之JSP入门
    js小例子之二级联动
    git常用命令
    centos下安装pip-python
    Pyspider抓取静态页面
    Python中__init__()方法注意点
    2、Pyspider使用入门
  • 原文地址:https://www.cnblogs.com/hyb1/p/3042179.html
Copyright © 2011-2022 走看看