我一直在嘗試運行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(成功)。 –
你有寫訪問該文件/目錄嗎? –