前言
这两天帮学校程序设计大赛出题,有部分题是自己出的。由于我觉得写题解很麻烦,所以用Python写了个生成测试用例文件的程序。(水了篇文章)
ansMaker源代码
这部分被我编成了一个模块,可以导入单独使用:
import subprocess
import os
class TestMaker:
def __init__(self, path: str, count: int, exefile: str):
self.__path = path
self.__exefile = exefile
self.__count = count
def __makeAns(self, testFileName):
while self.__count > 0:
self.__testFileName = testFileName
print(f"第{self.__count}次输入数据")
argsList = input().split()
input_data = '\n'.join(argsList) # 保持为字符串形式
print("input finish")
inFile = os.path.join(self.__path,
f"{testFileName}_{self.__count}.in")
outFile = os.path.join(self.__path,
f"{testFileName}_{self.__count}.out")
with open(inFile, 'w') as f:
for temp in argsList:
f.write(temp + ' ')
print("inFile scanf succ")
result = subprocess.run([self.__exefile],
capture_output=True,
input=input_data,
text=True)
with open(outFile, 'w') as f:
f.write(result.stdout)
print("outFile scanf succ")
self.__count -= 1
print("The test produce succ!")
def make(self):
print("Input the test file name:")
fileName = input()
self.__makeAns(fileName)
if __name__ == '__main__':
pass
else:
print("ansMaker succ be import")
原理很简单,调用题解生成的exe文件,然后将终端输入的数据作为标准输入流给exe文件,再将exe文件的输出(标准输出流)获取后,放到.out文件中,输入放入.in文件中。
测试main函数
import ansMaker
ansMaker = ansMaker.TestMaker("./", 3, "test.exe")
ansMaker.make()
缺点
- 输入数据的时候按回车就结束了,有的题目的数据再输入的时候可能需要换行,由于设计的原因这里都只能用空格进行分隔了