如何获取终端完整历史记录及保存Python程序CMD全部输出
捕获Python程序CMD输出的简便方案
不需要手动实现,Python的subprocess模块里就有现成的内置方法可以轻松获取全部输出:
使用
subprocess.run()(Python 3.5及以上版本可用),这是官方推荐替代Popen的高层API,能直接捕获标准输出和错误输出:import subprocess # 示例:运行目标Python脚本test.py result = subprocess.run( ["python", "test.py"], capture_output=True, text=True, # 以字符串形式返回输出,替代旧版的universal_newlines=True check=False # 设为True会在子进程返回非0码时抛出异常,按需选择 ) # 提取全部输出内容 stdout_content = result.stdout stderr_content = result.stderr # 保存到文件 with open("full_output.log", "w", encoding="utf-8") as f: f.write("标准输出:\n" + stdout_content) f.write("\n错误输出:\n" + stderr_content)如果需要基于
Popen实现,也可以用内置的communicate()方法一次性获取所有输出,无需手动循环读取:import subprocess process = subprocess.Popen( ["python", "test.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 等待进程结束并获取全部输出 stdout, stderr = process.communicate() # 保存内容 with open("full_output.log", "w", encoding="utf-8") as f: f.write(stdout) f.write(stderr)
注意点:
capture_output=True等价于同时设置stdout=subprocess.PIPE和stderr=subprocess.PIPE- 必须同时处理
stdout和stderr,否则可能因缓冲区满导致子进程卡住 text=True避免了手动解码字节流的麻烦,直接返回字符串格式的输出
内容的提问来源于stack exchange,提问作者Omar Yacop
相关产品推荐
相关产品推荐

