2014-06-27 31 views
1

我使用paramiko登錄設備並運行一些命令,然後僅捕獲相關輸出。代碼的相關部分看起來是這樣的:使用python在文本文件中查找出現第n個詞的實例

stdin, stdout, stderr = ssh.exec_command('show interface') 
print stdout.read() 

這給出了以下的輸出:

Ethernet interface 0:0 
Internet address:  171.182.204.207 netmask 255.255.255.0 
Internet address:  fe80::2d0:83ff:fe06:4c67 prefixlen 64 
MTU size:    1500 
Link status:   configured to full duplex, 1 gigabit/sec network 
Member of the bridge: none 
Ethernet interface 0:1 
Internet address:  fe80::2d0:83ff:fe06:4c66 prefixlen 64 
MTU size:    1500 
Link status:   autosensed to full duplex, 1 gigabit/sec network 
Member of the bridge: none 

現在出了這一點,我想只有鏈路狀態,所以我這樣做:

stdin, stdout, stderr = ssh.exec_command('show interface') 
link = '\n'.join(item for item in stdout.read().splitlines() if 'Link' in item) 
print link 

,現在我得到這樣的:

Link status:   configured to full duplex, 1 gigabit/sec network 
Link status:   autosensed to full duplex, 1 gigabit/sec network 

工作正常。但是,我想要的是在我的列表理解中指定出現次數,這樣我只能得到關鍵字Link的第一次,第二次或第n次出現。

回答

2

你有三種選擇。

將所有項目存儲在列表中,然後使用索引。但是,這將在內存中創建一個不必要的名單:

links = [item for item in stdout.read().splitlines() if 'Link' in item] 
index = 5 
print links[index] 

或者使用itertools.islice,並傳遞給它的生成器創建您的代碼中使用過:

from itertools import islice 
index = 5 
links = (item for item in stdout.read().splitlines() if 'Link' in item) 
print next(islice(links, index, index+1)) 

甚至使用以下生成器可以更好地使用itertools.islice。下面是我沒有使用任何.read().splitlines()因爲他們讀到的一切到內存:

links = (item for item in stdout if 'Link' in item) 
print next(islice(links, index, index+1)) 

您還可以使用item.startswith('Link')如果你只希望只在字符串的開始匹配'Link',但如果你想要在字符串中的任何地方匹配它,然後忽略它。

+0

+1,用於確保只有相關內容被讀入內存的選項。 – Amistad

1

爲什麼不只是索引你的列表理解?

links = [item for item in stdout.read().splitlines() if 'Link' in item] 
print links[n] # index here 
+0

'\ n'.join將每個字符分成一個新行。只是打印鏈接[n]工作.. however謝謝索引的想法.. – Amistad

+0

哎呀!你是對的。修正了。 – Lynn

1
occurence = 2 
link = [item for item in stdout.read().splitlines() if 'Link' in item][occurence] 
相關問題