我用Python编写了这个简单的脚本:
import os
os.system("ping www.google.com")
它正在从cmd的windows中以交互模式工作,但是如果我在IDLE上写(它看起来像是黑色的cmd屏幕),它似乎不起作用。这是第一个问题。
我喜欢做的第二件事是: 我想将ping的结果保存在一个文件中 我该怎么办?
我是Python的新手(两天);) 非常感谢。
答案 0 :(得分: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