2014-10-03 204 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

相关问题