简体   繁体   English

输出到命令行并以python脚本写入文件

[英]Output to command line and write to file in python script

I have a python script that currently outputs a bunch of text to stdout (the terminal). 我有一个python脚本,当前将一堆文本输出到stdout(终端)。 It looks something like: 看起来像:

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

Right now all of this output just goes to stdout; 现在,所有这些输出都将输出到stdout。 however, I want the output to be written to a file in addition to writing to the terminal. 但是, 除了写入终端,我还希望将输出写入文件。 What is the best way to do this? 做这个的最好方式是什么? Ideally I don't want to have to change all of the print statements (to another method call for instance), and I don't have access to some of the code is called to do the printing. 理想情况下,我不需要更改所有的print语句(例如,更改为另一个方法调用),并且我无权访问某些被称为执行打印的代码。

I was thinking, is there someway I can redirect print output to both stdout AND a file? 我在想,是否可以将打印输出重定向到stdout和文件?

open a file and write your string in it: 打开文件并在其中写入字符串:

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

and if you want to redirect your output to a file use > in terminal after invoke the .py file : 如果您想将输出重定向到文件,请在调用.py文件后在终端中使用>

$~ python my_file.py > save_file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM