如何实现标准输入输出的包装?
我有一个互动程序,它使用标准输入和标准输出。
我需要创建一个包装器,这个包装器会把X发送到程序的标准输入,然后检查程序是否输出Y,接着再把包装器的标准输入和标准输出重定向到程序的标准输入和标准输出,就像直接运行程序一样。
我该怎么实现这个呢?X和Y可以直接写死在代码里。用Bash还是Python比较好呢?
编辑:我不能运行这个程序两次,必须只有一个实例。以下是伪代码:
def wrap(cmd, in, expected_out):
p = exec(cmd)
p.writeToStdin(in)
out = p.readBytes (expected_out.size())
if (out != expected_out) return fail;
# if the above 4 lines would be absent or (in == "" and out == "")
# then this wrapper would be exactly like direct execution of cmd
connectpipe (p.stdout, stdout)
connectpipe (stdin, p.stdin)
p.continueExecution()
4 个回答
0
你可以覆盖系统模块中的输入和输出。
import sys
sys.stdin, sys.stdout = wrapper.stdin, wrapper.stdout
这些需要是分别用于读取和写入的文件对象。原始的输入和输出可以在这里找到:
sys.stdin, sys.stdout = sys.__stdin__, sys.__stdout__
1
假设X和Y是文件,而且你可以多次运行这个程序:
#!/bin/bash
test "`program <X`" = "`cat Y`" && program
或者,如果你想让程序出错时说得更详细一些:
#!/bin/bash
if [[ `program <X` != `cat Y` ]]; then
echo -e "Assertion that input X produces Y failed, exiting."
exit 1
fi
program
如果你只运行这个程序一次,使用Expect会比临时改变标准文件输入输出简单得多。
3
Expect 是一个用来自动化运行其他程序的工具。简单来说,你可以用普通的文本写下这样的指令:
启动这个程序。当它显示出“username”这个词时,就发送我的用户名。当它显示“password”时,就发送我的密码。
这个工具非常适合用来控制其他程序的运行。