在Python中解析标准输出

18 投票
4 回答
56038 浏览
提问于 2025-04-15 18:15

在Python中,我需要获取一个外部程序的版本,这个程序我会在我的脚本里调用。

假设我想在Python中使用Wget,并且我想知道它的版本。

我会调用

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

然后我会解析输出的字符串。

怎么把os.command的输出结果重定向到一个字符串里呢?

4 个回答

-2

subprocess 来代替吧。

10

使用 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]
42

一种“老”的方法是:

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

另一种现代的方法是使用 subprocess 模块:

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

撰写回答