[英]How to implement a stdin, stdout wrapper?
我有一個運行stdin和stdout的交互式程序。 我需要創建將X發送到它的stdin的包裝器,檢查它是否打印Y然后將包裝器的stdin和stdout重定向到程序的stdin和stdout,就像程序將直接執行一樣。
怎么實現這個? X和Y可以硬編碼。 擊? 蟒蛇?
編輯:我無法運行程序兩次。 它必須是一個例子。 這是偽代碼:
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()
假設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是一種比動態重新分配標准文件I / O更簡單的替代方法。
您可以覆蓋sys模塊的stdin和stdout
import sys
sys.stdin, sys.stdout = wrapper.stdin, wrapper.stdout
這些需要分別是為讀寫而打開的文件對象。 最初的stdin和stdout在
sys.stdin, sys.stdout = sys.__stdin__, sys.__stdout__
我對你究竟想要達到的目標感到有些困惑; 據我所知,你希望:
如果是這種情況,你想這樣做:
exec()
並執行目標程序。 exec()
放入目標程序中。 如果這是正確的,我可以提供一個~30行C程序,或~10行Python程序,實現這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.