有没有办法检查特定程序是否正在运行(使用Python)?

时间:2017-03-24 21:41:19

标签: python

如何检查特定的python文件是否正在通过另一个python文件运行? 例如在python file1中会有一个条件:

if file.IsRunning:

我试过:

__author__ = 'Cyber-01'
import psutil

def IsRunning(name):
    for pid in psutil.pids():
        try:
            p = psutil.Process(pid)
            if len(p.cmdline())>1:
                if name in p.cmdline()[1]:
                    return True
        except:
            None
    return False

if running("server.py"):
    print "yes"

但无论

,它总是返回是

1 个答案:

答案 0 :(得分:4)

首先-尝试:

import psutil

def running(name):
    name_list = []
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
            if name in pinfo['name']:
                return True
            else:
                pass
        except:
            return False

修改

更符合OP原始帖子的解决方案:

def running3(program, scriptname):
    for pid in psutil.pids(): # Iterates over all process-ID's found by psutil,  
        try:
            p = psutil.Process(pid) # Requests the process information corresponding to each process-ID, the output wil look (for example) like this: <psutil.Process(pid=5269, name='Python') at 4320652312>
            if program in p.name(): # checks if the value of the program-variable that was used to call the function matches the name field of the plutil.Process(pid) output (see one line above). So it basically calls <psutil.Process(pid=5269, name='Python') at 4320652312>.name() which is --> 'Python'
                """Check the output of p.name() on your system. For some systems it might print just the program (e.g. Safari or Python) on others it might also print the extensions (e.g. Safari.app or Python.py)."""
                for arg in p.cmdline(): # p.cmdline() echo's the exact command line via which p was called. So it resembles <psutil.Process(pid=5269, name='Python') at 4320652312>.cmdline() which results in (for example): ['/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python', 'Start.py'], it then iterates over is splitting the arguments. So in the example you will get 2 results: 1 = '/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python' and 2 = 'Start.py'. It will check if the given script name is in any of these.. if so, the function will return True.
                    if scriptname in str(arg):  
                        return True
                    else:
                        pass
            else:
                pass
        except:
            continue

if running3('Python', 'server.py'):
    print("Yes, the specified script is running!")
else:
    print("Nope, can't find the damn process..")

至于为什么OP的代码不起作用:

我可以在代码中看到一些错误。首先,return False的缩进将它置于for循环之外,从而创建一个函数将始终返回False的情况。

此外,psutil.Process.cmdline()返回用于执行当前进程的命令。当调用psutil.Process.cmdline(1)时,它应该返回命令行,通过该命令行调用PID 1的进程。但是,这似乎会引发很多权限错误。反过来,这会导致if len(p.cmdline())>1几乎一直失败,引发异常,从而在OP的代码中返回None

第二次EDIT(测试两种​​解决方案以获得最佳性能)

  • 代码1(使用psutil.process_iter()):100个循环,最好3个:每个循环4.37毫秒
  • 代码2(使用psutil.Process(pid).name()):1000循环,最佳3:945每循环usec
  • 结论:第二个代码似乎是您最好的选择!