我一直在尝试运行Java程序并将其STDOUT输出捕获到Python脚本的文件中。想法是通过我的程序运行测试文件,并检查其是否与答案匹配。
按照这个和这个问题,使用subprocess.call
是必经之路。在下面的代码中,我正在执行subprocess.call(command, stdout=f)
f是我打开的文件。
结果文件为空,我不太明白为什么。
import glob
test_path = '/path/to/my/testfiles/'
class_path = '/path/to/classfiles/'
jar_path = '/path/to/external_jar/'
test_pattern = 'test_case*'
temp_file = 'res'
tests = glob.glob(test_path + test_pattern) # find all test files
for i, tc in enumerate(tests):
with open(test_path+temp_file, 'w') as f:
# cd into directory where the class files are and run the program
command = 'cd {p} ; java -cp {cp} package.MyProgram {tc_p}'
.format(p=class_path,
cp=jar_path,
tc_p=test_path + tc)
# execute the command and direct all STDOUT to file
subprocess.call(command.split(), stdout=f, stderr=subprocess.STDOUT)
# diff is just a lambda func that uses os.system('diff')
exec_code = diff(answers[i], test_path + temp_file)
if exec_code == BAD:
scream(':(')
我检查了文档,subprocess
并建议使用subprocess.run
(在Python 3.5中添加)。该run
方法返回的实例CompletedProcess
,该实例具有一个stdout
字段。我检查了一下,这stdout
是一个空字符串。这解释了为什么f
我尝试创建的文件为空。
即使退出代码从到0(成功)subprocess.call
,也并不意味着我的Java程序实际上已执行。我最终command
分为两个部分来修复此错误。
如果您注意到,我最初尝试cd
进入正确的目录,然后执行Java文件-全部合为一体command
。我最终cd
从中删除command
并os.chdir(class_path)
改为执行。在command
现在仅包含字符串运行Java程序。这成功了。
因此,代码如下所示:
good_code = 0
# Assume the same variables defined as in the original question
os.chdir(class_path) # get into the class files directory first
for i, tc in enumerate(tests):
with open(test_path+temp_file, 'w') as f:
# run the program
command = 'java -cp {cp} package.MyProgram {tc_p}'
.format(cp=jar_path,
tc_p=test_path + tc)
# runs the command and redirects it into the file f
# stores the instance of CompletedProcess
out = subprocess.run(command.split(), stdout=f)
# you can access useful info now
assert out.returncode == good_code
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句