2015-03-13 58 views
0

我是新來的python和工作traceroute,所以我想知道是否有可能將整個python traceroute結果輸出到txt和Csv文件?任何想法我怎麼能做到這一點,因爲我找不到任何適當的顯示如何做到這一點。是否可以將整個python輸出寫入文本或csv文件?

感謝

+0

它需要從python腳本內完成編寫O/P! – 2015-03-13 18:51:22

回答

2
import subprocess 

with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output: 
    for host in hostlist: 
     host = host.strip() 

     print "Tracing", host 

     trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

     while True: 
      hop = trace.stdout.readline() 

      if not hop: break 

      print '-->', hop.strip() 
      output.write(hop) 

     # When you pipe stdout, the doc recommends that you use .communicate() 
     # instead of wait() 
     # see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait 
     trace.communicate() 

我從主機列表讀取主機的詳細信息,並在文件中