2010-01-20 4 views
10

Python에서 스크립트에서 호출해야하는 외부 바이너리의 버전을 가져와야합니다.Python에서 stdout 구문 분석

파이썬에서 Wget을 사용하고 싶습니다. 버전을 알고 싶습니다.

나는

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

를 호출 한 후 나는 출력 된 문자열을 구문 분석합니다.

os.command의 stdout을 파이썬의 문자열로 리디렉션하는 방법은 무엇입니까?

+1

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

답변

34

하나 "오래된"방법은 다음과 같습니다

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

고맙습니다. ghostdog75! AFeG –

+0

"새로운"방법이란 무엇입니까? –

+1

subprocess는 파이썬 2.4부터 새로 추가되었습니다. – kroiz

0

대신 subprocess을 사용하십시오.

+1

감사합니다! Ignacio! AFeG –

+0

'Subprocess.popen'은 쉘을 호출하여 명령을 구문 분석하고 Python에서 추가 프로세스를 실행합니다. –

+0

@Grijesh : 당신이 말한다면. –

9

사용 subprocess 모듈 :

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

당신이 만약

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

다른 현대적인 방법은 subprocess 모듈을 사용하는 것입니다 * nix에, 나는 당신에게 명령 모듈을 사용하는 것이 좋습니다 것입니다.

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

py3k에 잘못된 조언이 없습니다. docs say : **'subprocess' ** 모듈을 사용하는 것이 명령 모듈. – SilentGhost

관련 문제