如何用os.system在Python中进行简单的ping并将结果保存到文件中
我写了一个简单的Python脚本:
import os
os.system("ping www.google.com")
这个脚本在Windows的命令行中可以正常运行,但在IDLE中运行时却出现了一个黑色的命令行窗口,这就是我遇到的第一个问题。
我还想做的第二件事是:我想把ping的结果保存到一个文件里。请问我该怎么做呢?
我刚学Python(才两天);)非常感谢!
1 个回答
0
你可以用 subprocess.check_output
来保存输出结果。
import subprocess
with open('output.txt','w') as out:
out.write(subprocess.check_output("ping www.google.com"))
output.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