繁体   English   中英

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

[英]Capture and parse output from external command inside Python

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

下面我写的代码执行dmidecode | 使用os.popen()的less命令,并将其输出存储到名为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

因此,现在我想解析一个值:Vendor,发行日期和版本,并且应该提供相关值。

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

帮帮我,我已经浏览过,但是没有可用的文档...

你有两个问题。 每个StackOverflow问题只打一个问题。 这仅解决第一个问题。

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

“运行带有参数的命令并返回其输出。”

例:

  import subprocess

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM