Python 通过PID获取进程名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4189717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:42:21  来源:igfitidea点击:

Get process name by PID

pythonprocesspid

提问by andyortlieb

This should be simple, but I'm just not seeing it.

这应该很简单,但我只是没有看到。

If I have a process ID, how can I use that to grab info about the process such as the process name.

如果我有进程 ID,我如何使用它来获取有关进程的信息,例如进程名称。

采纳答案by Juho ?stman

Under Linux, you can read proc filesystem. File /proc/<pid>/cmdlinecontains the commandline.

在 Linux 下,您可以读取 proc 文件系统。文件/proc/<pid>/cmdline包含命令行。

回答by slezica

Try PSUtil -> https://github.com/giampaolo/psutil

尝试 PSUtil -> https://github.com/giampaolo/psutil

Works fine on Windows and Unix, I recall.

我记得在 Windows 和 Unix 上运行良好。

回答by user3818650

For Windows

对于 Windows

A Way to get all the pids of programs on your computer without downloading any modules:

一种无需下载任何模块即可获取计算机上所有程序 pid 的方法:

import os

pids = []
a = os.popen("tasklist").readlines()
for x in a:
      try:
         pids.append(int(x[29:34]))
      except:
           pass
for each in pids:
         print(each)

If you just wanted one program or all programs with the same name and you wanted to kill the process or something:

如果您只想要一个程序或所有具有相同名称的程序,并且您想终止该进程或其他内容:

import os, sys, win32api

tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()

print(tasklistr)

def kill(process):
     process_exists_forsure = False
     gotpid = False
     for examine in tasklistrl:
            if process == examine[0:len(process)]:
                process_exists_forsure = True
     if process_exists_forsure:
         print("That process exists.")
     else:
        print("That process does not exist.")
        raw_input()
        sys.exit()
     for getpid in tasklistrl:
         if process == getpid[0:len(process)]:
                pid = int(getpid[29:34])
                gotpid = True
                try:
                  handle = win32api.OpenProcess(1, False, pid)
                  win32api.TerminateProcess(handle, 0)
                  win32api.CloseHandle(handle)
                  print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
                except win32api.error as err:
                  print(err)
                  raw_input()
                  sys.exit()
    if not gotpid:
       print("Could not get process pid.")
       raw_input()
       sys.exit()

   raw_input()
   sys.exit()

prompt = raw_input("Which process would you like to kill? ")
kill(prompt)

That was just a paste of my process kill program I could make it a whole lot better but it is okay.

那只是我的进程终止程序的粘贴,我可以让它变得更好,但没关系。

回答by Neil McGill

Try this

尝试这个

def filter_non_printable(str):
    ret=""
    for c in str:
        if ord(c) > 31 or ord(c) == 9:
            ret += c
        else:
            ret += " "
    return ret

#
# Get /proc/<cpu>/cmdline information
#
def pid_name(self, pid):
    try:
        with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile:
            return filter_non_printable(pidfile.readline())

    except Exception:
        pass
        return

回答by KBill

Using psutil, here is the simplest code i can give you:

使用 psutil,这是我可以给你的最简单的代码:

import psutil

# The PID ID of the process needed
pid_id = 1216

# Informations of the Process with the PID ID
process_pid = psutil.Process(pid_id)
print(process_pid)
# Gives You PID ID, name and started date
# psutil.Process(pid=1216, name='ATKOSD2.exe', started='21:38:05')

# Name of the process
process_name = process_pid.name()