2016-08-16 64 views
0

快速提問;所以基本上我試圖打印爲下面的結果,如果關鍵詞是發現如果找到字符串打印n較早的行

Keyword = ['Dn'] 
Output =     ISIS Protocol Information for ISIS(523) 
       --------------------------------------- 
SystemId: 0101.7001.1125  System Level: L2  
Area-Authentication-mode: NULL 
Domain-Authentication-mode: NULL 
Ipv6 is not enabled 
ISIS is in restart-completed status 
Level-2 Application Supported: MPLS Traffic Engineering 
L2 MPLS TE is not enabled 
ISIS is in protocol hot standby state: Real-Time Backup 

Interface: 10.170.11.125(Loop0) 
Cost: L1 0   L2 0     Ipv6 Cost: L1 0 L2 0  
State: IPV4 Up       IPV6 Down 
Type: P2P        MTU: 1500  
Priority: L1 64 L2 64 
Timers:  Csnp: L12 10 , Retransmit: L12 5 , Hello: 10 , 
Hello Multiplier: 3   , LSP-Throttle Timer: L12 50 

Interface: 10.164.179.218(GE0/5/0) 
Cost: L1 10  L2 10    Ipv6 Cost: L1 10 L2 10 
State: IPV4 Mtu:Up/Lnk:Dn/IP:Dn   IPV6 Down 
Type: BROADCAST       MTU: 9497  
Priority: L1 64 L2 64 
Timers:  Csnp: L1 10 L2 10 ,Retransmit: L12 5 , Hello: L1 10 L2 
Hello Multiplier: L1 3 L2 3  , LSP-Throttle Timer: L12 50 

Interface: 10.164.179.237(GE0/6/0) 
Cost: L1 1000  L2 1000    Ipv6 Cost: L1 10 L2 10 
State: IPV4 Up       IPV6 Down 
Type: BROADCAST       MTU: 9497  
Priority: L1 64 L2 64 
Timers:  Csnp: L1 10 L2 10 ,Retransmit: L12 5 , Hello: L1 10 L2 10 , 
Hello Multiplier: L1 3 L2 3  , LSP-Throttle Timer: L12 50 

因此,如果「DN」輸出打印發現最後兩行,所以預期輸出應該

Interface: 10.164.179.218(GE0/5/0) 
Cost: L1 10  L2 10    Ipv6 Cost: L1 10 L2 10 
State: IPV4 Mtu:Up/Lnk:Dn/IP:Dn   IPV6 Down 

使用摘錄如下:

with open(host1 + ".txt","w") as f: 

      else: 

        if (">") in output: 

          output = net_connect.send_command("screen-length 0 temporary", delay_factor=1) 
          print (output) 
          output = net_connect.send_command("dis isis brief", delay_factor=1) 
          print (output) 
          f.write(output) 


hosts = open((hostsfile) , "r") 
keys = ['Dn'] 
hosts = [hosts for hosts in (hosts.strip() for hosts in open(hostsfile)) if  hosts] 
for host2 in hosts: 
    for line in f: 
    for keywords in keys: 
     if keywords in line: 
      print (line) 

我希望這可以解釋,也親切地忽略,如文件操作等小問題,作爲主要關注的是輸出的N-2行,如果字符串中發現

回答

2

使用collections.deque來存儲n行(collections.deque(maxlen=n)),並在找到關鍵字時在deque中打印行。

3

對於collections.deque這是一個很好的用例。可以說你想打印匹配的行和前兩行(這就是我想你想要基於你的例子認爲)。我們可以通過包裝每行到雙端隊列做到這一點,那麼當我們找到一個匹配,我們打印整個雙端隊列:

from collections import deque 

def print_deque(dqu): 
    for item in dqu: 
     print(item) 

lines = deque(maxlen=3) 
with open('filename') as file_input: 
    for line in file_input: 
     lines.append(line) 
     if 'Dn' in line: 
      print_deque(lines) 

這工作,因爲deque會悄悄丟棄最早的項目,當您嘗試添加一些超越它的最大長度。

+0

謝謝你;快速的;我該如何從輸出中刪除雙轉換:(對不起,我只是開始學python – Saadi381

+0

@ saadi381 - 對不起,錯字...它應該是'print(item)',而不是'print(dqu)'。 – mgilson