【问题标题】:How to make a simple ping and save the result in a file in Python with os.system [duplicate]如何使用os.system进行简单的ping并将结果保存在Python文件中[重复]
【发布时间】:2026-01-11 21:15:02
【问题描述】:

我用 Python 编写了这个简单的脚本:

import os
os.system("ping www.google.com")

它在 windows 的 cmd 中以交互模式工作,但如果我在 IDLE 上写它似乎不起作用(它出现一个 cmd 黑屏)。这是第一个问题。

我喜欢做的第二件事是: 我想将 ping 的结果保存在一个文件中 我该怎么做?

我是 Python 新手(两天);) 非常感谢。

【问题讨论】:

标签: python ping


【解决方案1】:

您使用subprocess.check_output 保存输出

    import subprocess
    with open('output.txt','w') as out:
        out.write(subprocess.check_output("ping www.google.com"))

输出.txt

Pinging www.google.com [74.125.236.178] with 32 bytes of data:

Reply from 74.125.236.178: bytes=32 time=31ms TTL=56

Reply from 74.125.236.178: bytes=32 time=41ms TTL=56

Reply from 74.125.236.178: bytes=32 time=41ms TTL=56

Reply from 74.125.236.178: bytes=32 time=32ms TTL=56



Ping statistics for 74.125.236.178:

    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

    Minimum = 31ms, Maximum = 41ms, Average = 36ms

【讨论】: