如果您的文件名为example.txt,请执行
diff example.txt <(program with all its options)
<() 语法将程序的输出放在括号中,并将其传递给diff 命令,就像它是一个文本文件一样。
编辑:
如果您只是想在if-clause 中检查文本文件和程序的输出是否相同,您可以这样做:
if [ "$(diff example.txt <(program with all its options))" == "" ]; then
echo 'the outputs are identical'
else
echo 'the outputs differ'
fi
即diff 仅在文件不同时才生成输出,因此空字符串作为答案意味着文件相同。
编辑 2:
原则上您可以将标准输入重定向到文件,如下所示:
program < input.txt
现在,无需进一步测试,我不知道这是否适用于您的 python 脚本,但假设您可以将程序期望的所有输入放入这样的文件中,您可以这样做
if [ "$(diff example.txt <(program < input.txt))" == "" ]; then
echo 'Great!'
else
echo 'Wrong output. You loose 1 point.'
fi
编辑 3::
我用python写了一个简单的测试程序(我们称之为program.py):
x = input('type a number: ')
print(x)
y = input('type another number: ')
print(y)
如果您在 shell 中使用python program.py 以交互方式运行它,并给出5 和7 作为答案,您会得到以下输出:
type a number: 5
5
type another number: 7
7
如果您创建一个文件,例如 input.txt,其中包含所有所需的输入,
5
7
并像这样将其通过管道传输到您的文件中:
python program.py < input.txt
你会得到以下输出:
type a number: 5
type another number: 7
差异的原因是 python(和许多其他 shell 程序)根据输入是来自交互式 shell、管道还是重定向的标准输入而对输入进行不同的处理。在这种情况下,输入不会回显,因为输入来自input.txt。但是,如果您使用 input.txt 同时运行您的代码和学生的代码,则这两个输出应该仍然具有可比性。
编辑 4:
正如下面的 cmets 所述,如果您只想知道它们是否不同,则无需将 diff 命令的整个输出与空字符串 ("") 进行比较,返回状态就足够了。最好在bash写一个小测试脚本(姑且称之为code_checker.sh),
if diff example.txt <(python program.py < input.txt) > /dev/null; then
echo "Great!"
else
echo "Wrong output. You loose 1 point."
fi
if 子句中的>/dev/null 部分将diff 的输出重定向到一个特殊设备,有效地忽略它。如果你有很多输出,最好使用cmp,就像 user1934428 提到的那样。