2013-04-23 162 views
5

我想在Windows 7上編寫一個Python腳本,它讀取命令ipconfig /displaydns的輸出並嘗試從輸出中獲取一些值。在Python中的命令輸出解析

ipconfig /displaydns"輸出是這樣的,

Windows IP Configuration 

9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts. 

Record Name . . . . . : 9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts. 
Record Type . . . . . : 1 
Time To Live . . . . : 294 
Data Length . . . . . : 4 
Section . . . . . . . : Answer 
A (Host) Record . . . : 127.0.0.16 

我藉此輸出和保存它下面的變量,

output = subprocess.check_output("ipconfig /displaydns", shell=True) 

當我打印「輸出」我得到的以下

b'\r\nWindows IP Configuration\r\n\r\n 9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.\r\n ----------------------------------------\r\n Record Name . . . . . : 9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.\r\n Record Type . . . . . : 1\r\n Time To Live . . . . : 289\r\n Data Length . . . . . : 4\r\n Section . . . . . . . : Answer\r\n A (Host) Record . . . : 127.0 .0.16\r\n\r\n\r\n' 

從這個輸出我對的值感興趣分別爲127.0.0.169.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.

我該如何在Python中做到這一點?

+0

o utput.split('')'? (編輯:編輯後,這是無效的) – Torxed 2013-04-23 17:18:00

回答

11
import subprocess 
output = subprocess.check_output("ipconfig /displaydns", shell=True) 
result = {} 
for row in output.split('\n'): 
    if ': ' in row: 
     key, value = row.split(': ') 
     result[key.strip(' .')] = value.strip() 

print(result) 
print(result['A (Host) Record']) 

給出:

{'A (Host) Record': '127.0 .0.16', 'Data Length': '4', 'Section': 'Answer', 'Record Name': '9.a.c.e.x-0.19-430f5091.531.1518.1b8d.2f4a.210.0.k1m2t5a3245k242qmfp75spjkv.avts.', 'Time To Live': '289', 'Record Type': '1'} 
127.0 .0.16 

另一種解決方案是: (當我在我的腦袋想到了這一點,我認爲這將是更緊湊..它不是,但無論如何,這是一種調用外部命令的不同方法,您可以在其中控制錯誤和輸出(您可以將兩者區分開來))

import subprocess 
cmdpipe = subprocess.Popen("ipconfig /displaydns", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 
result = {} 
for row in cmdpipe.stdout.readline(): 
    if ': ' in row: 
     key, value = row.split(': ') 
     result[key.strip(' .')] = value.strip() 

print(result) 
print(result['A (Host) Record']) 
+0

謝謝。它完美的作品。非常感謝。 – user2253876 2013-04-24 15:52:34

+0

@ user2253876不客氣,不要忘記標記你的答案(它給了我內心的愉悅):) – Torxed 2013-04-25 09:19:00