2010-11-15 130 views
24

這應該很簡單,但我只是沒有看到它。通過PID獲取進程名稱

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

+0

的可能重複[你如何在python程序的進程id?](http://stackoverflow.com/questions/3761639/how-do-you-get python中的程序代碼) – 2014-07-23 15:58:17

+2

@PeterO。這個問題是這個**的反向**。 – 2015-02-13 13:56:18

回答

20

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

+6

另一種方法是'ps -o cmd = '。 – 2013-01-16 17:05:14

+7

而'/ proc//comm'實際上給出了進程名稱。 – 2013-07-05 15:01:23

13

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

適用於Windows和Unix很好,我記得。

+0

這似乎是正確的做法。它讓我感到它不在debian 5中。 – andyortlieb 2010-11-16 14:08:09

+2

這是Debian的(常見)問題,而不是與psutil;) – 2011-06-23 22:01:18

+1

你可以「python setup.py install」從源代碼安裝它。 – 2011-08-04 11:17:28

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) 

這只是我的一個進程kill程序的貼我可以使它好多了,但它是好的。

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