2010-09-21 5 views
55

ich einige Monitoring-Skripte in Python zu schreiben und ich versuche, die sauberste Weg zu finden, die Prozess-ID eines beliebigen laufenden Programm der Name des ProgrammsWie erhalten Sie die Prozess-ID eines Programms in Unix oder Linux mit Python?

so etwas wie

ps -ef | grep MyProgram 

gegeben zu bekommen ich konnte die Ausgabe, dass analysiere aber ich dachte, es könnte

+0

installiert werden, wenn Sie Kreuz arbeiten möchten -Plattform (zB ebensogut unter Linux, Mac, Solaris, ...) gibt es keinen besseren Weg als die 'pf' Ausgabe zu parsen. Wenn es für eine einzelne, sehr spezifische Plattform ist, editieren Sie bitte Ihr Q, um die offensichtlich entscheidenden Informationen (genaue OS-Versionen, die Sie anvisieren müssen) * und * das Tag hinzuzufügen! –

+0

Sie können die Ausgabe der PS direkt in Python analysieren – Mark

Antwort

9

Versuchen pgrep. Sein Ausgabeformat ist viel einfacher und daher leichter zu analysieren.

222

From the standard library ein besserer Weg in python sein:

os.getpid() 
+21

Das bekommt die PID des Python-Prozesses nicht, was der Benutzer fragt – Mark

+65

Es ist jedoch eine sehr gute Antwort für den Titel der Frage –

+10

Ja, es hat mir was ich kam hierher für. – Jorvis

14

Wenn Sie sich nicht auf die Standardbibliothek beschränken, mag ich dafür psutil.

Zum Beispiel zu finden, "Python" Prozesse:

>>> import psutil 
>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']] 
[{'name': 'python3', 'pid': 21947}, 
{'name': 'python', 'pid': 23835}] 
+0

Können Sie bitte ein Beispiel für das gleiche geben. –

+0

Aus Mangel an Beispiel – Paullo

3

Für Windows

Ein Weg, um alle PIDs Programme auf Ihrem Computer zu erhalten, ohne Module Download:

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) 

Wenn Sie nur ein Programm oder alle Programme mit dem gleichen Namen gesucht und Sie wollten den Prozess oder etwas zu töten:

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) 

das war nur eine Paste aus meinem Prozess Programm kill ich es viel besser machen könnte, aber es ist in Ordnung.

-1

Die Aufgabe kann mit dem folgenden Code gelöst werden, wobei [0:28] das Intervall ist, in dem der Name gehalten wird, während [29:34] die tatsächliche PID enthält.

import os 

program_pid = 0 
program_name = "notepad.exe" 

task_manager_lines = os.popen("tasklist").readlines() 
for line in task_manager_lines: 
    try: 
     if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces 
      program_pid = int(line[29:34]) 
      break 
    except: 
     pass 

print(program_pid) 
4

auch: Python: How to get PID by process name?

Anpassung an den vorherigen geschrieben Antworten.

def getpid(process_name): 
    import os 
    return [item.split()[1] for item in os.popen('tasklist').read().splitlines()[4:] if process_name in item.split()] 

getpid('cmd.exe') 
['6560', '3244', '9024', '4828'] 
0

Für Posix (Linux, BSD, etc ... müssen nur Verzeichnis/proc montiert werden) ist es einfacher, mit os-Dateien in/proc

Werke auf Python 2 und 3 (Die einzige Arbeit Unterschied ist die Ausnahme-Struktur, daher die "außer Ausnahme", die ich nicht mögen, aber beibehalten, um Kompatibilität zu halten. Auch könnte benutzerdefinierte Ausnahme erstellt haben.

)
#!/usr/bin/env python 

import os 
import sys 


for dirname in os.listdir('/proc'): 
    if dirname == 'curproc': 
     continue 

    try: 
     with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd: 
      content = fd.read().decode().split('\x00') 
    except Exception: 
     continue 

    for i in sys.argv[1:]: 
     if i in content[0]: 
      # dirname is also the number of PID 
      print('{0:<12} : {1}'.format(dirname, ' '.join(content))) 

Beispielausgabe (es funktioniert wie pgrep):

phoemur ~/python $ ./pgrep.py bash 
1487   : -bash 
1779   : /bin/bash 
1

Mit psutil:

(mit [sudo] pip install psutil)

import psutil 

# Get current process pid 
current_process_pid = psutil.Process().pid 
print(current_process_pid) # e.g 12971 

# Get pids by program name 
program_name = 'chrome' 
process_pids = [process.pid for process in psutil.process_iter() if process.name == program_name] 
print(process_pids) # e.g [1059, 2343, ..., ..., 9645] 
Verwandte Themen