如何访问 bash 中的文件并将其内容与 运行 程序中的标准输出进行比较以确保它们相同?

How can I access a file in bash and compare its contents with stdout when running a program to make sure they are identical?

如何比较程序标准输出中的输出与输出文件中的模型输出?我问是因为我正在尝试制作评分脚本。另外,我正在考虑使用 -q grep,但我不确定我将如何使用它。

请简单回答,因为我是 bash 的菜鸟。

重要编辑:

我想在 if 语句中使用它。例如:

if(modle_file.txt is identical to stdout when running program); then
    echo "Great!"
else
    echo "Wrong output. You loose 1 point."

编辑:

程序接受输入。例如,如果我们这样做:

%Python3 Program.py
Enter a number: 5
The first 5 (arbitrary) things are:
2, 5, etc  (program output)

%

一种方法是将 stdout 输出重定向到一个文件,如下所示:

myCommand > /folder/file.txt

然后运行一个diff命令来比较两个文件

diff /folder/file.txt /folder/model_output.txt

编辑:要在 if 语句中使用它,您可以执行以下操作:

if [ -z "$(diff /folder/file.txt /folder/model_output.txt 2>&1)" ]; then echo "Great!"; else echo "Wrong output. You loose 1 point."; fi

如果文件相等,则打印Great!,否则打印Wrong output. You loose 1 point.

如果您的文件名为 example.txt,请执行

diff example.txt <(program with all its options)

<() 语法将程序的输出放在括号中并将其传递给 diff 命令,就好像它是文本文件一样。

编辑:

如果你只想检查if子句中的文本文件和程序的输出是否相同,你可以这样做:

if [ "$(diff example.txt <(program with all its options))" == "" ]; then
  echo 'the outputs are identical'
else
  echo 'the outputs differ'
fi

diff 仅在文件不同时生成输出,因此空字符串作为答案表示文件相同。

编辑 2:

原则上你可以将 stdin 重定向到一个文件,像这样:

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 交互,并给出 57 作为答案,你会得到以下输出:

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:

正如下面的评论之一所述,如果您只想知道它们是否不同,则没有必要将 diff 命令的整个输出与空字符串 ("") 进行比较,return状态就够了。最好在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 的输出重定向到一个特殊设备,有效地忽略它。如果你有很多输出,最好使用 user1934428 提到的 cmp

既然你对实际差异不感兴趣,只关心它们是否相同,我认为cmp是最好的选择(如果文件大,速度更快):

if cmp -s example.txt <(your program goes here)
then
  echo identical
fi

请注意,这只比较标准输出(如您所要求的),而不是标准错误。