如何将Python终端输出的ping结果写入TXT文件?
实现Ping结果存入TXT文件
方法一:命令行重定向(快速修改原代码)
直接在os.system的ping命令后追加重定向符号,让命令行输出直接写入文件:
import os import time while True: # >> 为追加模式,每次结果会添加到文件末尾;用 > 则会清空文件后写入新内容 os.system('ping 1.1.1.1 -n 1 >> ping_results.txt') time.sleep(5)
运行后同目录会生成ping_results.txt,所有ping结果都会自动追加进去。
方法二:用subprocess模块(更灵活可控)
os.system是较老的用法,Python推荐用subprocess处理外部命令,能更灵活捕获输出,还可自定义内容格式:
import subprocess import time while True: # 获取当前时间戳,方便标记ping时间 current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 执行ping命令并捕获输出 result = subprocess.run( ['ping', '1.1.1.1', '-n', '1'], capture_output=True, text=True, encoding='gbk' # Windows下cmd默认编码为gbk,Linux/macOS替换为utf-8 ) # 以追加模式打开文件写入内容 with open('ping_results.txt', 'a', encoding='utf-8') as f: f.write(f"=== Ping时间: {current_time} ===\n") f.write(result.stdout) # 若ping失败,把错误信息也写入文件 if result.stderr: f.write(result.stderr + '\n') f.write('\n') # 分隔每次ping的结果 time.sleep(5)
这个方法的优势:
- 可自定义输出格式(比如添加时间戳)
- 同时捕获正常输出和错误信息
- 完全用Python控制文件写入,不依赖命令行重定向
系统适配提示
Linux/macOS系统下,ping命令的次数参数是-c而非-n,需把命令改为ping 1.1.1.1 -c 1
内容的提问来源于stack exchange,提问作者SpinierYard212
相关产品推荐
相关产品推荐

