通过进程ID获取进程名称

26

这应该很简单,但我就是没找到方法。

如果我有一个进程ID,如何使用它来获取关于该进程的信息,比如进程名称。


3
@PeterO. 那个问题与这个问题相反。 - Piotr Dobrogost
5个回答

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

6
另一种选择是使用ps -o cmd=<pid>命令。 - Ricardo Stuven
10
/proc/<pid>/comm 实际上提供了进程的名称。 - Skippy le Grand Gourou

15

那似乎是正确的做法。但它没有在Debian 5中,这让我感到不爽。 - andyortlieb
2
这是Debian的常见问题,而不是psutil的问题 ;) - Paweł Polewicz
1
你可以直接运行命令 "python setup.py install" 来安装它。 - Giampaolo Rodolà
我同意你们的观点,如果是在特定的服务器上,我也会这样做。但是我们正在分发的应用程序目前仅支持debian 5。在这种情况下,读取/proc将更容易、更可靠,有助于我们长期管理。 - andyortlieb
我正在使用p.name(),但输出被截断了。有没有其他方法可以获取完整的进程名称? - Ravi Shanker Reddy

3

针对Windows系统

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

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)

如果您只想要一个程序或所有同名程序,并且您想要终止该进程或其他操作:
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)

这只是我结束进程的程序的复制粘贴,我可以让它变得更好,但现在已经可以了。


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

使用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()

0

试试这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接