【问题标题】:is it possible to write entire python output to a text or csv file?是否可以将整个 python 输出写入文本或 csv 文件?
【发布时间】:2015-03-13 18:50:17
【问题描述】:

我是 python 的新手并且正在研究 traceroute,所以我想知道是否可以将整个 python traceroute 结果输出写入 txt 和 Csv 文件?知道如何实现这一目标,因为我找不到任何合适的方法来说明如何做到这一点。

谢谢

【问题讨论】:

  • 它需要在 python 脚本中完成!

标签: python csv save output


【解决方案1】:
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 写入文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多