从Python内部的外部命令捕获并解析输出

时间:2015-09-26 07:02:59

标签: python

虽然我是python的新手,我写了数组列表,我想打印bios信息数组列表?如何在此脚本中执行外部命令并捕获输出并解析它。

下面的代码我写了执行dmidecode | less命令使用os.popen()并将其输出存储到名为package的变量:

#!/usr/bin/python
import os
f = os.popen("dmidecode | less")
package = f.read()
print 'Bios Information is:',package

执行上面的代码后:sudo python sample.py =>输出如下:

BIOS Information
    Vendor: *****
    Version: 1.40
    Release Date: 09/07/2009
    ROM Size: 1024 kB
    Characteristics:
            PCI is supported
            BIOS is upgradeable
            BIOS shadowing is allowed
            Boot from CD is supported
            Selectable boot is supported
            BIOS ROM is socketed
            EDD is supported
            Japanese floppy for NEC 9800 1.2 MB is supported (int 13h)
            Japanese floppy for Toshiba 1.2 MB is supported (int 13h)
            5.25"/360 kB floppy services are supported (int 13h)
            5.25"/1.2 MB floppy services are supported (int 13h)
            3.5"/720 kB floppy services are supported (int 13h)
            3.5"/2.88 MB floppy services are supported (int 13h)
            8042 keyboard services are supported (int 9h)
            CGA/mono video services are supported (int 10h)
            ACPI is supported
            USB legacy is supported
            Targeted content distribution is supported

所以现在我要解析一个值:供应商,发布日期&版本和那应该提供相关的值。

问题是我必须在上面的脚本中执行外部命令,捕获输出并解析它? 所以任何人都可以帮我找出这个问题?

帮帮我,我已浏览但没有文件可用......

1 个答案:

答案 0 :(得分:0)

你有两个问题。每个StackOverflow问题只有一个问题。这只涉及第一个。

要从程序中捕获stdout或stderr输出,可以使用subprocess.check_output()

“使用参数运行命令并返回其输出。”

示例:

  import subprocess

  output = subprocess.check_output("dmidecode")
  print(output.decode("utf-8"))  # Convert from bytes to string

当您输出可用时,您可以询问如何解析它,以及您想要对解析的数据做什么。