如何使用Subprocess同时保存输出并在终端查看输出?
实现subprocess命令输出同时显示在终端并保存
我来给你分享两种实用的解决思路,既能保存命令输出,又能实时在终端看到内容:
方法1:借助系统tee命令(简单快捷)
如果你用的是类Unix系统(Linux/macOS),或者Windows上用PowerShell,可以直接借助系统自带的tee命令——它本来就是专门做“同时输出到终端和文件”这件事的。
示例代码:
import subprocess # 执行ls命令,同时把输出打印到终端并保存到output.txt # shell=True允许我们使用管道符| result = subprocess.run( 'ls | tee output.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) # 如果需要把输出存在Python变量里,直接取result.stdout即可 saved_output = result.stdout print("\n===== 刚才保存的输出内容 =====") print(saved_output)
注意:
shell=True虽然方便,但如果命令里包含用户输入的内容,要警惕注入风险;Windows cmd里没有tee,得用PowerShell的tee或者Out-File -Append替代。
方法2:纯Python实现(跨平台更安全)
如果想要跨平台兼容,或者不想依赖shell,我们可以用subprocess.Popen实时读取输出流,一边打印到终端,一边保存内容。
示例代码:
import subprocess def run_and_log(cmd, output_file="output.txt"): full_output = [] # 启动子进程,设置实时输出模式 with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, # 行缓冲,保证实时输出 universal_newlines=True ) as proc: # 逐行读取输出 for line in proc.stdout: # 打印到终端 print(line, end='') # 保存到列表 full_output.append(line) # 同时写入文件(如果需要实时写文件,这里可以打开文件追加) with open(output_file, 'a') as f: f.write(line) # 拼接完整输出字符串 full_output_str = ''.join(full_output) return proc.returncode, full_output_str # 使用示例:执行ls命令 return_code, output_content = run_and_log(['ls']) # 验证保存的内容 print("\n===== 从变量读取的保存内容 =====") print(output_content)
这个方法的好处是完全由Python控制,不依赖任何系统工具,Windows/Linux/macOS都能用,而且能实时看到输出,也能把内容存在变量或文件里。
内容的提问来源于stack exchange,提问作者Mooseyoose
相关产品推荐
相关产品推荐

