2010-01-20 9 views
10

In Python muss ich die Version eines externen binären erhalten, die ich in meinem Skript aufrufen muss.Parsing eines Stdout in Python

Nehmen wir an, ich möchte Wget in Python verwenden und ich möchte seine Version wissen.

werde ich

os.system("wget --version | grep Wget") 

rufen und dann werde ich die ausgegebene Zeichenfolge analysieren.

Wie Umleitung der Stdout der os.command in einer Zeichenfolge in Python?

+1

Duplikat: http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python – SilentGhost

Antwort

34

Ein "alter" Weg ist:

fin,fout=os.popen4("wget --version | grep Wget") 
print fout.read() 

Die andere moderne Art und Weise ist einen subprocess Modul zu verwenden:

import subprocess 
cmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE) 
for line in cmd.stdout: 
    if "Wget" in line: 
     print line 
+0

Danke ghostdog75! AFeG –

+0

Was ist der "neue" Weg? –

+1

Subprozess ist neu seit Python 2.4. – kroiz

0

Verwenden Sie stattdessen subprocess.

+1

Danke Ignacio! AFeG –

+0

ruft 'Subprocess.popen' die Shell auf, um den Befehl zu parsen und führt einen zusätzlichen Prozess in Python aus. –

+0

@Grijesh: Nur wenn du es sagst. –

9

Verwenden Sie das subprocess Modul:

from subprocess import Popen, PIPE 
p1 = Popen(["wget", "--version"], stdout=PIPE) 
p2 = Popen(["grep", "Wget"], stdin=p1.stdout, stdout=PIPE) 
output = p2.communicate()[0] 
-1

Wenn Sie Sind on * nix, würde ich dir empfehlen, das Modul commands zu benutzen.

import commands 

status, res = commands.getstatusoutput("wget --version | grep Wget") 

print status # Should be zero in case of of success, otherwise would have an error code 
print res # Contains stdout 
+0

falscher Hinweis: existiert in py3k nicht, Dokumentation sagt: Die Verwendung des Moduls ** 'subprocess' ** ist besser als die Verwendung des Befehlsmodul. – SilentGhost