为何subprocess.check_output不显示子进程抛出异常前的输出?
问题原因解析
subprocess.check_output()的核心行为导致了这个现象:
- 当子进程**正常退出(退出码为0)**时,它会返回子进程的标准输出(stdout),主进程随后可以打印这些内容。
- 当子进程**非零退出(比如抛出异常导致崩溃)**时,它会直接抛出
CalledProcessError异常,此时主进程的代码还没执行到print(subprocess.check_output(...))这一步就被中断了,自然无法输出子进程的"HELLO WORLD"内容。
简单说,file2.py里的print()确实输出了内容,但因为check_output在子进程异常时直接抛错,主进程没机会获取并打印这个输出。
解决方法
如果想要在子进程抛出异常时也能拿到并显示它的输出,可以改用subprocess.run(),或者在check_output外层加异常捕获:
方法1:捕获CalledProcessError异常
修改file1.py如下:
import subprocess print("Going to run file1") try: output = subprocess.check_output(["python", "file2.py"], stderr=subprocess.STDOUT) print(output.decode("utf-8")) except subprocess.CalledProcessError as e: # 即使子进程异常,也能获取到它的输出 print(e.output.decode("utf-8"))
方法2:使用subprocess.run()
run()方法不管子进程是否正常退出,都会返回包含stdout和stderr的结果对象:
import subprocess print("Going to run file1") result = subprocess.run(["python", "file2.py"], capture_output=True, text=True) # 打印子进程的标准输出 print(result.stdout) # 如果需要查看异常信息,也可以打印标准错误 # print(result.stderr)
内容的提问来源于stack exchange,提问作者pseudodev
相关产品推荐
相关产品推荐

