在python中通过命令查找进程 [英] Find processes by command in python
问题描述
在我的 Python 脚本中,我想检查 otherscript.py
当前是否正在 (Linux) 系统上运行.psutil 库看起来是一个不错的解决方案:
In my Python script, i want to check if otherscript.py
is currently being run on the (Linux) system. The psutil library looked like a good solution:
import psutil
proc_iter = psutil.process_iter(attrs=["name"])
other_script_running = any("otherscript.py" in p.info["name"] for p in proc_iter)
问题在于 p.info["name"]
只给出了一个进程的可执行文件的名称,而不是完整的命令.因此,如果在系统上执行 python otherscript.py
,p.info["name"]
将只是该进程的 python
,并且我的脚本无法检测 otherscript.py
是否是正在运行的脚本.
The problem is that p.info["name"]
only gives the name of the executable of a process, not the full command. So if python otherscript.py
is executed on the system, p.info["name"]
will just be python
for that process, and my script can't detect whether or not otherscript.py
is the script being run.
是否有一种简单的方法可以使用 psutil 或其他一些库进行此检查?我意识到我可以将 ps
命令作为子进程运行并在输出中查找 otherscript.py
,但如果存在,我更喜欢更优雅的解决方案.
Is there a simple way to make this check using psutil or some other library? I realize i could run the ps
command as a subprocess and look for the otherscript.py
in the output, but i'd prefer a more elegant solution if one exists.
推荐答案
不知道这样行不行
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
other_script_running = any("otherscript.py" in p.info["cmdline"] for p in proc_iter)
这篇关于在python中通过命令查找进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!