You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在重定向输入时将程序输入同步插入到输出中?

重定向输入时让程序输出包含输入内容的实现方法

我需要实现这样的效果:当程序通过输入重定向(比如从文件或管道读取输入)运行时,把输入内容插入到程序的输出中,模拟交互式控制台的运行过程——就像用户手动在控制台输入一样。这主要用于编程课程的作业批改,方便查看程序的输入和对应输出。

举个例子,有如下C语言程序:

#include <stdio.h>

int main() {
  double x, y;
  printf("Soma de dois números:\n");
  printf("Digite o primeiro número: ");
  scanf("%lf", &x);
  printf("Digite o segundo número: ");
  scanf("%lf", &y);
  double soma = x + y;
  printf("%lf + %lf = %lf\n", x, y, soma);
  return 0;
}

当用echo -e "10\n25\n" | ./a.out运行时,期望输出是:

Soma de dois números:
Digite o primeiro número: 10
Digite o segundo número: 25
10.000000 + 25.000000 = 35.000000

下面是几种可行的实现方式:

1. 使用系统自带的script命令(Linux/Unix)

script是大多数类Unix系统自带的工具,用于记录终端会话的所有输入输出。直接用它就能模拟交互式场景:

echo -e "10\n25" | script -q -c './a.out' /dev/null

参数说明:

  • -q:静默模式,不显示script的启动/结束提示
  • -c './a.out':指定要运行的程序
  • /dev/null:把记录文件指向空设备,只在终端输出结果

这种方法无需额外安装工具,适合快速验证。

2. 使用expect工具

expect专门用于处理交互式程序的自动化,可以精准控制输入时机并同步输出:
先写一个interact.exp脚本:

spawn ./a.out
send "10\n"
send "25\n"
interact

然后运行:

expect interact.exp

它会模拟用户手动输入的过程,把程序的提示和输入内容一并输出。如果输入内容来自文件,也可以修改脚本读取文件内容发送。

3. 自定义Python包装脚本

如果需要更灵活的定制(比如批量处理作业、格式统一),可以写一个简单的Python脚本,手动处理程序的输入输出:

import subprocess
import sys

def run_interactive(prog_path, input_lines):
    # 启动目标程序,建立管道通信
    proc = subprocess.Popen(
        [prog_path],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )
    
    input_idx = 0
    # 逐行读取程序输出
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        # 打印程序的输出内容
        print(line.rstrip('\n'))
        # 如果还有输入未发送,就发送并打印输入内容
        if input_idx < len(input_lines):
            input_val = input_lines[input_idx]
            proc.stdin.write(f"{input_val}\n")
            proc.stdin.flush()
            print(input_val)
            input_idx += 1
    
    # 处理程序剩余的输出
    remaining_output = proc.stdout.read()
    if remaining_output:
        print(remaining_output.rstrip('\n'))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"用法: {sys.argv[0]} <程序路径> [输入文件]")
        sys.exit(1)
    
    target_prog = sys.argv[1]
    # 读取输入内容:从文件或标准输入
    if len(sys.argv) == 3:
        with open(sys.argv[2], 'r', encoding='utf-8') as f:
            inputs = [line.strip() for line in f if line.strip()]
    else:
        inputs = [line.strip() for line in sys.stdin if line.strip()]
    
    run_interactive(target_prog, inputs)

用法示例:

# 从管道读取输入
echo -e "10\n25" | python wrapper.py ./a.out

# 从文件读取输入
python wrapper.py ./a.out input.txt

这个脚本可以根据需求修改,比如调整输出格式、添加错误处理等,非常适合作业批改的批量场景。

内容的提问来源于stack exchange,提问作者Romildo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:25:50