使用Python将程序的输出重定向到文件:特定错误

时间:2016-11-28 04:57:06

标签: python scripting

我一直在尝试运行Java程序并将其STDOUT输出捕获到Python脚本中的文件中。我的想法是通过我的程序运行测试文件,并检查它是否与答案匹配。

根据thisthis个问题,使用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(':(')

1 个答案:

答案 0 :(得分:0)

我检查了subprocess subprocess.run,他们建议使用run(在Python 3.5中添加)。 CompletedProcess方法返回stdout的实例,该实例具有stdout字段。我检查过它,f是一个空字符串。这解释了我尝试创建的文件subprocess.call为空的原因。

即使退出代码为command的0(成功),但这并不意味着我的Java程序实际上已被执行。我最终通过将cd分解为两部分来修复此错误。

如果您注意到,我最初尝试command进入正确的目录,然后执行Java文件 - 一个cd。我最终从command删除了os.chdir(class_path)并改为commandgood_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 现在只包含运行Java程序的字符串。这样做了。

所以,代码看起来像这样:

.scene {
  position: absolute;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
}