是否有方法检查特定程序是否正在运行(使用Python)?
如何检查特定的python文件是否正在通过另一个python文件运行? 例如,在python文件1中,将有一个条件:是否有方法检查特定程序是否正在运行(使用Python)?,python,Python,如何检查特定的python文件是否正在通过另一个python文件运行? 例如,在python文件1中,将有一个条件: if file.IsRunning: 我曾尝试: __author__ = 'Cyber-01' import psutil def IsRunning(name): for pid in psutil.pids(): try: p = psutil.Process(pid) if len(p.cmdli
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"
但无论第一次尝试,它总是返回yes(是):
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..")
def running3(程序,脚本名):
对于psutil.pids()中的pid:#迭代psutil找到的所有进程ID,
尝试:
p=psutil.Process(pid)#请求与每个进程ID对应的进程信息,输出(例如)如下所示:
p.name()中的if program:#检查用于调用函数的程序变量的值是否与plutil.Process(pid)输出的name字段匹配(参见上面的一行)。所以它基本上调用.name()这是-->'Python'
“”“检查系统上p.name()的输出。对于某些系统,它可能只打印程序(例如Safari或Python),而对于其他系统,它也可能打印扩展名(例如Safari.app或Python.py)。”“”
对于p.cmdline()中的arg:#p.cmdline()echo是调用p的确切命令行。因此,它类似于.cmdline(),它的结果是(例如):['/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python','Start.py'],然后它迭代以拆分参数。因此,在本例中,您将得到两个结果:1='/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python'和2='Start.py'。它将检查给定的脚本名称是否在其中任何一个中。。如果是,函数将返回True。
如果脚本名在str(arg)中:
返回真值
其他:
通过
其他:
通过
除:
持续
如果运行3('Python','server.py'):
打印(“是,指定的脚本正在运行!”)
其他:
打印(“不,找不到该死的流程…”)
至于OP的代码不起作用的原因:
我可以在代码中看到一些错误。首先,return False
的缩进将其置于for循环之外,从而创建函数始终返回False
的情况
此外,psutil.Process.cmdline()
返回用于执行当前进程的命令。调用psutil.Process.cmdline(1)
时,它应该返回调用PID 1进程的命令行。然而,这似乎引发了许多权限错误。这反过来会导致if len(p.cmdline())>1
几乎一直失败,引发异常,从而在OP的代码中返回None
第二次编辑(测试两种解决方案的最佳性能)
- 代码1(使用psutil.process_iter()):100个循环,每个循环最好3:4.37毫秒
- 代码2(使用
psutil.Process(pid.name()
):1000个循环,最好是每个循环3:945usec - 结论:第二个代码似乎是你最好的选择强>
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..")
def running3(程序,脚本名):
对于psutil.pids()中的pid:#迭代psutil找到的所有进程ID,
尝试:
p=psutil.Process(pid)#请求与每个进程ID对应的进程信息,输出(例如)如下所示:
p.name()中的if program:#检查用于调用函数的程序变量的值是否与plutil.Process(pid)输出的name字段匹配(参见上面的一行)。所以它基本上调用.name(),它是-->'Python'
“”“检查系统上p.name()的输出。对于某些系统,它可能只打印程序(例如Safari或Python),而对于其他系统,它也可能打印扩展名(例如Safari.app或Python.py)。”“”
对于p.cmdline()中的arg:#p.cmdline()echo是调用p的确切命令行。因此,它类似于.cmdline(),它的结果是(例如):['/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python','Start.py'],然后它迭代以拆分参数。因此,在本例中,您将得到两个结果:1='/Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python'和2='Start.py'。它将检查给定的脚本名称是否在其中任何一个中。。如果是,函数将返回True。
如果脚本名在str(arg)中:
返回真值
其他:
通过
其他:
通过
除:
持续
如果运行3('Python','server.py'):
打印(“是,指定的脚本正在运行!”)
其他:
打印(“不,找不到该死的流程…”)
至于OP的代码不起作用的原因:
我可以在代码中看到一些错误。首先,return False
的缩进将其置于for循环之外,从而创建函数始终返回False
的情况
此外,psutil.Process.cmdline()
返回用于执行当前进程的命令。调用psutil.Process.cmdline(1)
时,它应该返回调用PID 1进程的命令行。然而,这似乎引发了许多权限错误。这反过来会导致if len(p.cmdline())>1
几乎一直失败,引发异常,从而在OP的代码中返回None
第二次编辑(测试两种解决方案的最佳性能)
- 代码1(使用psutil.process\u iter()):100个循环,bes