如何将subprocess.run的输入值包含在stdout文本文件中
我希望我的自动评分系统有一个功能,就是把学生提交的输出结果写入一个txt文件。然后,这个生成的txt文件会和另一个包含预期输出的txt文件进行比较,比较的结果会决定学生的最终成绩。我已经成功生成了学生的txt文件,但我不太喜欢这个txt文件的格式。对于我提供给subprocess.run
的input
参数,输入值本身没有被写入,而所有询问这些值的提示信息都在同一行上。
比如,以下测试案例生成的txt文件格式是这样的:
测试案例1: ["103\n", "-3\n", "85\n"]
测试案例2: ["-10\n", "-1\n", "105\n" ,"98\n"]
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: This program calculates the letter grade from the integer quiz grade
Enter quiz grade: This program calculates the letter grade from the integer quiz grade
Enter quiz grade: Your quiz letter grade is BThis program calculates the letter grade from the integer quiz grade
Enter quiz grade: This program calculates the letter grade from the integer quiz grade
Enter quiz grade: This program calculates the letter grade from the integer quiz grade
Enter quiz grade: This program calculates the letter grade from the integer quiz grade
Enter quiz grade: Your quiz letter grade is A
这样的格式很难阅读。我想知道有没有什么外部功能或者特别的参数可以放在subprocess.run
里,这样生成的输出就和实际运行学生提交的代码时看到的输出一模一样?我想要的输出是:
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: 103
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: -3
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: 85
Your quiz letter grade is B
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: -10
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: -1
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: 105
This program calculates the letter grade from the integer quiz grade
Enter quiz grade: 98
Your quiz letter grade is A
代码:
input_value_lists = [["103\n", "-3\n", "85\n"],
["-10\n", "-1\n", "105\n","98\n"]]
with open(student_txt_file, "w") as txt_file:
for list in input_value_lists:
for input_value in list:
output = subprocess.run(["java", hw_file], input=input_value, capture_output=True, text=True)
txt_file.write(output.stdout)
我最开始以为可以直接把输入值写进txt文件,但这样会导致输入值在生成的输出之前。我也在查阅subprocess
的文档,但我要么理解错了(这很有可能),要么真的没有什么参数可以包含输入值。
1 个回答
0
你的用词有点不太准确。你说“确切的输出”,但“103”和“-3”其实不是输出,它们是输入。没错,这些内容在终端上会显示出来,但这并不意味着它们是输出。
在Python中无法实现你想要的功能,因为输入是交错在一起的。你可以修改Java代码,让它回显输入。你的Java程序可以判断标准输出(stdout)是否连接到终端,并根据这个情况改变它的行为,甚至可以传递另一个参数来告诉它当前不是一个实时终端。