在python中通过命令查找进程

时间:2017-10-27 16:24:15

标签: python process psutil

在我的Python脚本中,我想检查当前是否在(Linux)系统上运行otherscript.pypsutil库看起来是一个很好的解决方案:

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是否为脚本正在运行。

有没有一种简单的方法可以使用psutil或其他库进行检查?我意识到我可以将ps命令作为子进程运行并在输出中查找otherscript.py,但如果存在,我更喜欢更优雅的解决方案。

3 个答案:

答案 0 :(得分:2)

我想知道这是否有效

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)

答案 1 :(得分:1)

http://psutil.readthedocs.io/en/latest/#find-process-by-name 看一下检查name(),cmdline()和exe()的第二个例子。

供参考:

import os
import psutil

def find_procs_by_name(name):
    "Return a list of processes matching 'name'."
    ls = []
    for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
        if name == p.info['name'] or \
                p.info['exe'] and os.path.basename(p.info['exe']) == name or \
                p.info['cmdline'] and p.info['cmdline'][0] == name:
            ls.append(p)
    return ls

答案 2 :(得分:0)

此代码正在检查进程。 不管Linux还是Window都没关系

import psutil

proc_iter = psutil.process_iter()
for i in proc_iter:
    print(i)