x
是一個帶有\r\n
行分隔符的字符串。每個「行」不以標準方式(例如製表符)分隔,而是由多個空格分隔。有probably an elegant way to handle this。
第一行是空的,第二行是標題,第三行只是-----
的一行,所以你需要從第4行到最後。
import subprocess
import re
p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE)
[x, err] = p.communicate()
items = x.split('\r\n')
for itm in items[3:]:
## convert this to a delimited line for ease of processing:
itm = re.sub('\s\s+', '\t', itm)
print(itm.split('\t')[-1])
結果:
或進一步細化:
import subprocess
import re
p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE)
[x, err] = p.communicate()
items = x.split('\r\n')
print('\n'.join(map(lambda itm: re.sub('\s\s+', '\t', itm).split('\t')[-1], items[3:])))
從評論更新
所以它瓦特雖然如果我喜歡4接口和我只想讀第一個,那麼最好的方法是什麼?我試圖尋找正則表達式,但無法找到一種方法來保持第一行並從結果中移除其餘部分。
你不需要這個正則表達式。我唯一使用正則表達式是將多個空間字符的任何實例轉換爲\t
(製表符)字符,以便我們可以使用split
輕鬆解析這些行。否則,你觀察到的,它會產生輸出,如'Local', 'Area', 'Network'
所以我上面假設你想打印出名字的所有,我們確定這些項目的標準輸出的4線開始的方法。這就是爲什麼我們做的:
for itm in items[3:]:
該行表示,「遍歷每個事情在items
,從第三事情直到最後的事情。」 This is a concept known as slicing可以在任何序列對象上進行(字符串,元組,列表等)
我有下面的連接,只是想知道第一連接名稱,並從我的結果中刪除休息。
所以我們不再需要迭代(這是如果我們需要處理每個項目完成)。我們知道,我們只需要一個項目,它是第一項目,這樣你就可以修改爲:
import subprocess
import re
p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE)
[x, err] = p.communicate()
## This gets the line-delimited list from stdout
items = x.split('\r\n')
## Now, we only need the fourth item in that list
itm = items[3]
## convert this to a delimited line for ease of processing:
itm = re.sub('\s\s+', '\t', itm)
## print to console
print(itm.split('\t')[-1])
或者,更簡潔:
import subprocess
import re
p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE)
[x, err] = p.communicate()
## This gets the line-delimited list from stdout
items = x.split('\r\n')
"""
Now, we only need the fourth item in that list
convert this to a delimited line for ease of processing,
and finally print to console
This is a one-line statement that does what 3 lines did above
"""
print(re.sub('\s\s+', '\t', items[3]).split('\t')[-1])
有你有任何機會嘗試解決方案如下 –
@DavidZemens是的,我還想再深入一層。 所以它按預期工作,但如果我有4個接口並且我只想讀第一個,那麼最好的方法是什麼?我試圖尋找正則表達式,但無法找到一種方法來保持第一行並從結果中移除其餘部分。我正在學習編程,並在提問之前盡力而爲。 例如:我有下面的連接,只是想知道第一個連接名稱,並從我的結果中刪除休息。 端口Ethernet 的Ethernet2 爲Ethernet3 以太網端口Ethernet4 – pylearner