使用 subprocess.call 将 ping 结果输出到文本文件

Output result of a ping with subprocess.call to a text file

我正在尝试使用 Python ping Windows 中的 IP 地址。我想将 ping 的结果输出到一个文本文件中,但我不知道如何使用 subprocess.call 函数来实现。我知道如何将变量写入文件,但我不知道如何将 subprocess.call 中的任何内容分配给变量。

例如,如果我执行 ping,我希望文本文件看起来像这样

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

我该怎么做?

如果你在合理的shell中调用ping(比如cmd.exe),你可以使用I/O重定向:

ping 127.0.0.1 > file

> 表示程序的输出被写入给定的文件。

如果您将其称为 python 子流程(不容易从您的问题中得出),您可以使用 Popen:

with open('output.txt', 'w') as output:
    process = subprocess.Popen('ping 127.0.0.1', stdout=output)
    process.communicate()