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

seg*_*ult 1 bash shell grep file piping

如何将程序 stdout 中的输出与输出文件中的模型输出进行比较?我问这个问题是因为我正在尝试制作评分脚本。另外,我正在考虑使用 -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."
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

%
Run Code Online (Sandbox Code Playgroud)

Tho*_*ühn 5

如果您的文件被调用example.txt,请执行

diff example.txt <(program with all its options)
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

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

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

编辑2

原则上,您可以将 stdin 重定向到文件,如下所示:

program < input.txt
Run Code Online (Sandbox Code Playgroud)

现在,无需进一步测试,我不知道这是否适用于您的 python 脚本,但假设您可以将程序期望的所有输入放入这样的文件中,您可以这样做

if [ "$(diff example.txt <(program < input.txt))" == "" ]; then
  echo 'Great!'
else
  echo 'Wrong output. You loose 1 point.'
fi
Run Code Online (Sandbox Code Playgroud)

编辑 3: :

我用 python 编写了一个简单的测试程序(我们称之为program.py):

x = input('type a number: ')
print(x)
y = input('type another number: ')
print(y)
Run Code Online (Sandbox Code Playgroud)

如果您在 shell 中使用python program.py、 并给出57作为答案以交互方式运行它,您将得到以下输出:

type a number: 5
5
type another number: 7
7
Run Code Online (Sandbox Code Playgroud)

如果您创建一个文件,例如input.txt,其中包含所有所需的输入,

5
7
Run Code Online (Sandbox Code Playgroud)

并将其通过管道传输到您的文件中,如下所示:

python program.py < input.txt
Run Code Online (Sandbox Code Playgroud)

你会得到以下输出:

type a number: 5
type another number: 7
Run Code Online (Sandbox Code Playgroud)

造成这种差异的原因是 python(和许多其他 shell 程序)根据输入是否来自交互式 shell、管道或重定向的 stdin,以不同的方式处理输入。在这种情况下,输入不会被回显,因为输入来自input.txt。但是,如果您使用 运行您的代码和学生的代码input.txt,则两个输出应该仍然具有可比性。

编辑4:

正如下面的注释之一所述,如果您只想知道它们是否不同,则无需将命令的整个输出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
Run Code Online (Sandbox Code Playgroud)

>/dev/null- 子句中的部分将if的输出重定向diff到特殊设备,从而有效地忽略它。如果你有很多输出,最好使用cmpuser1934428 提到的那样。