简体   繁体   English

如何使用Python在Linux中通过pid获取进程名称?

[英]How to get the process name by pid in Linux using Python?

I want to get the process name, given it's pid in python.我想获取进程名称,因为它是 python 中的 pid。 Is there any direct method in python? python中有没有直接的方法?

The psutil package makes this very easy. psutil包使这很容易。

import psutil

process = psutil.Process(pid)

process_name = process.name()

If you want to see the running process, you can just use os module to execute the ps unix command 如果要查看正在运行的进程,可以使用os模块执行ps unix命令

import os
os.system("ps")

This will list the processes. 这将列出进程。

But if you want to get process name by ID, you can try ps -o cmd= <pid> So the python code will be 但是如果你想通过ID获取进程名,你可以尝试ps -o cmd= <pid>所以python代码将是

import os
def get_pname(id):
    return os.system("ps -o cmd= {}".format(id))
print(get_pname(1))

The better method is using subprocess and pipes. 更好的方法是使用subprocess和管道。

import subprocess
def get_pname(id):
    p = subprocess.Popen(["ps -o cmd= {}".format(id)], stdout=subprocess.PIPE, shell=True)
    return str(p.communicate()[0])
name = get_pname(1)
print(name)

Command name (only the executable name):命令名称(仅可执行文件名称):

from subprocess import PIPE, Popen

def get_cmd(pid)
    with Popen(f"ps -q {pid} -o comm=", shell=True, stdout=PIPE) as p:
        return p.communicate()[0]

Command with all its arguments as a string:命令及其所有参数作为字符串:

from subprocess import PIPE, Popen

def get_args(pid)
    with Popen(f"ps -q {pid} -o cmd=", shell=True, stdout=PIPE) as p:
        return p.communicate()[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM