我是python的新手并且正在研究traceroute所以我想知道是否可以将整个python traceroute结果输出写入txt和Csv文件?任何想法我怎么能实现这一点,因为我找不到任何一个显示如何做到这一点。
感谢
答案 0 :(得分: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()
我正在从主机列表中读取主机详细信息并将o / p写入文件