子進(jìn)程命令的實(shí)時(shí)輸出我使用python腳本作為流體力學(xué)代碼的驅(qū)動(dòng)程序。當(dāng)需要運(yùn)行模擬時(shí),我使用subprocess.Popen若要運(yùn)行代碼,請(qǐng)將stdout和stderr的輸出收集到subprocess.PIPE-然后我可以打印(并保存到日志文件)輸出信息,并檢查任何錯(cuò)誤。問題是,我不知道代碼是如何進(jìn)行的。如果我直接從命令行運(yùn)行它,它會(huì)給出關(guān)于迭代時(shí)間、下一次步驟的輸出,等等。是否有一種方法既可以存儲(chǔ)輸出(用于日志記錄和錯(cuò)誤檢查),也可以生成實(shí)時(shí)流輸出?我代碼的相關(guān)部分:ret_val = subprocess.Popen( run_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )output,
errors = ret_val.communicate()log_file.write(output)print outputif( ret_val.returncode ):
print "RUN failed\n\n%s\n\n" % (errors)
success = Falseif( errors ): log_file.write("\n\n%s\n\n" % errors)最初我是在run_command貫通tee這樣,一個(gè)副本直接進(jìn)入日志文件,流仍然直接輸出到終端-但是這樣我就不能存儲(chǔ)任何錯(cuò)誤(根據(jù)我的知識(shí))。編輯:臨時(shí)解決辦法:ret_val = subprocess.Popen( run_command, stdout=log_file, stderr=subprocess.PIPE, shell=True )while not ret_val.poll():
log_file.flush()然后,在另一個(gè)終端運(yùn)行tail -f log.txt(第二節(jié))log_file = 'log.txt').
子進(jìn)程命令的實(shí)時(shí)輸出
慕田峪4524236
2019-07-15 10:40:17