我一直在尝试运行Java程序并从Python脚本中将其STDOUT输出捕获到文件中。这个想法是通过我的程序运行测试文件,并检查它是否符合答案。使用Python将程序中的输出重定向到文件:特定错误
每this和this SO问题,使用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(':(')
有很多原因,你的文件是空的第一...通过替换在命令行中与实际值的变量执行的命令,看看你'使用正确的命令! –
我试过了,命令是正确的。我也尝试使用w/o分割命令并传递'''shell = True'''。我也试过'''subprocess.check_call(command.split(),stdout = PIPE)'''状态为0(成功)。 –
你有写访问该文件/目录吗? –