【发布时间】:2015-03-13 18:50:17
【问题描述】:
我是 python 的新手并且正在研究 traceroute,所以我想知道是否可以将整个 python traceroute 结果输出写入 txt 和 Csv 文件?知道如何实现这一目标,因为我找不到任何合适的方法来说明如何做到这一点。
谢谢
【问题讨论】:
-
它需要在 python 脚本中完成!
我是 python 的新手并且正在研究 traceroute,所以我想知道是否可以将整个 python traceroute 结果输出写入 txt 和 Csv 文件?知道如何实现这一目标,因为我找不到任何合适的方法来说明如何做到这一点。
谢谢
【问题讨论】:
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()
我正在从主机列表中读取主机详细信息并将 o/p 写入文件
【讨论】: