通过PID获取进程名

问题描述 投票:25回答:5

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

如果我有一个进程ID,我怎么可以用它来抓取有关过程信息,如进程名。

python process pid
5个回答
20
投票

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


14
投票

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

适用于Windows和Unix很好,我记得。


1
投票

对于Windows

一个办法让你的计算机上的程序所有的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)

如果你只是想一个程序或具有相同名称的所有程序和你想杀死进程或东西:

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)

这只是我的过程杀程序的贴我可以使它好多了,但它是好的。


1
投票

使用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
© www.soinside.com 2019 - 2024. All rights reserved.