簡體   English   中英

通過PID獲取進程名稱

[英]Get process name by PID

這應該很簡單,但我只是沒有看到它。

如果我有進程ID,我該如何使用它來獲取有關進程的信息,例如進程名稱。

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

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

我記得在Windows和Unix上運行良好。

對於Windows

無需下載任何模塊即可在計算機上獲取所有程序的方法:

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)

這只是我的進程終止程序的粘貼我可以使它好多了但是沒關系。

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

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM