簡體   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