如何在python中使用pid在pid中获取进程名称?

问题描述:

我想获取进程名称,因为它在python中是pid.python中有任何直接方法吗?

I want to get the process name, given it's pid in python. Is there any direct method in python?

如果要查看正在运行的进程,只需使用 os 模块执行 ps Unix命令

If you want to see the running process, you can just use os module to execute the ps unix command

import os
os.system("ps")

这将列出进程.

但是,如果要通过ID获取进程名称,可以尝试 ps -o cmd =< pid> 因此python代码将是

But if you want to get process name by ID, you can try ps -o cmd= <pid> So the python code will be

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

更好的方法是使用 subprocess 和管道.

The better method is using subprocess and pipes.

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)