如何让subprocess.run执行程序时stdin内容同步写入stdout输出文件
Windows环境下subprocess运行程序实现输入回显的解决方案
问题根因
手动在终端运行程序时,用户输入的内容会被终端自动回显到标准输出,因此会呈现「提示词+输入内容」的完整效果。通过文件重定向标准输入(stdin=userInput)时,程序直接从文件读取输入,没有终端负责回显输入内容,最终输出文件只会保留程序自身打印的提示词和输出结果,不会出现输入的Bob、27内容。
无第三方依赖实现方案
无需修改学生提交的程序,仅调整你的调用代码即可,适配所有使用标准输入的程序场景:
import subprocess # 读取预设的所有输入内容 with open("userInput.txt", "r", encoding="utf-8") as f: input_list = f.read().splitlines() with open("output.txt", "w", encoding="utf-8") as fout, open("error.txt", "w", encoding="utf-8") as ferr: # 加 -u 参数禁用Python输出缓冲,避免Windows环境下输出顺序错乱 proc = subprocess.Popen( ["python", "-u", "hello.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=ferr, text=True ) input_index = 0 output_buffer = "" while True: # 逐字符读取程序输出,避免阻塞 current_char = proc.stdout.read(1) if not current_char: break output_buffer += current_char fout.write(current_char) # 识别input()的等待输入特征:输出以冒号加空格结尾,还有未发送的输入 if output_buffer.endswith(": ") and input_index < len(input_list): # 将输入内容写入输出文件,模拟终端回显 user_input = input_list[input_index] + "\n" fout.write(user_input) fout.flush() # 将输入发送给子进程 proc.stdin.write(user_input) proc.stdin.flush() input_index += 1 output_buffer = ""
运行后生成的output.txt内容完全符合预期:
Your name: Bob Your age: 27 Hello, Bob you are 27 years old
适配其他语言程序的说明
如果需要批改C/C++等其他语言编写的学生程序,仅需替换subprocess.Popen的启动命令为对应程序的执行路径,同时添加对应语言的禁用输出缓冲参数即可,整体交互逻辑无需修改。
内容的提问来源于stack exchange,提问作者rainerpm
相关产品推荐
相关产品推荐

