2014-10-03 42 views
0

我有一個python腳本,目前輸出一堆文本到stdout(終端)。它看起來像這樣:輸出到命令行並寫入到python腳本中的文件

print "ABC" 
print "CD" 
print "QR" 
methodCallToOtherCodeThatAlsoPrints() 
# A bunch of other print lines... 

現在所有這些輸出只是stdout;不過,我希望將輸出寫入文件另外要寫入終端。做這個的最好方式是什麼?理想情況下,我不希望必須更改所有打印語句(以另一個方法調用爲例),並且我無法訪問某些打印的代碼。

我在想,有沒有辦法將打印輸出重定向到stdout和文件?

+3

這個問題看起來類似:http://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-file-and-console-with-scripting。 Amith Koujalgi有一個答案,看起來好像會對你有用。 – MikeTheReader 2014-10-03 18:36:35

回答

0

打開一個文件,並在寫你的字符串:

with open('my_file' , 'w') as f: 
    f.write('your_string') 

,如果你想給你的輸出重定向到終端文件使用>調用.py文件後:

$~ python my_file.py > save_file.txt 
+1

我認爲OP希望程序的行爲如同被調用爲'python program.py | tee日誌文件「。 – 5gon12eder 2014-10-03 18:39:08

+0

創建一個f.write並打印並使用搜索和替換以將當前方法更改爲新方法的方法。 – Elric 2014-10-03 19:08:52

相關問題