简体   繁体   English

在文件和终端标准输出python 2.7中打印输出

[英]Print output in file and terminal stdout python 2.7

I've added the following line to a python file in order to output all print strings to a file: 我已将以下行添加到python文件中,以便将所有print字符串输出到文件中:

sys.stdout = open(logf, 'wb')

This does what I wanted, but also stops all print strings from appearing in the terminal. 这可以实现我想要的功能,但是也可以阻止所有print字符串出现在终端中。 Is there a way to configure stdout to print to both destinations? 有没有一种方法可以将stdout配置为打印到两个目的地? (I'm trying to avoid writing a function for each use of print because there are many and it's a lot to rewrite. Also, I've perused several similar topics, but I haven't found a simple method.) (我试图避免为每次使用print编写函数,因为有很多重写的内容。而且,我仔细研究了几个类似的主题,但是我没有找到一种简单的方法。)

def fprint(output):
    print output
    with open("somefile.txt", "a") as f:
        f.write("{}\n".format(output))

This function would do it for you, use instead of print. 此功能将为您完成,使用而不是打印。

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

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