如何在python中使用pid在pid中获取进程名称? [英] How to get the process name by pid in Linux using Python?

查看:86
本文介绍了如何在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)

这篇关于如何在python中使用pid在pid中获取进程名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆