【问题标题】:How do I log the contents of print messages to two files with stdout如何使用 stdout 将打印消息的内容记录到两个文件中
【发布时间】:2013-06-16 19:13:34
【问题描述】:

寻找一些帮助记录/保存打印到如下所示的两个文件位置,有人知道这样做的方法吗?

### Create output file/open it for editing
output_file = open('FILE.txt','w')
output_file1 = open('FILE_APPENDING.txt','a')

## Create a backup of current setting
old_stdout = sys.stdout

sys.stdout = output_file
sys.stdout = output_file1

print "stuff here"
## loop here printing stuff

## Revert python to show prints as normal
sys.stdout=old_stdout

## Close the file we are writing too
output_file.close()
output_file1.close()

提前致谢 - 海福克斯

【问题讨论】:

  • 为什么不直接使用file.write

标签: python logging python-2.7 stdout output


【解决方案1】:

您可以使用写入多个文件的某个类重新分配sys.stdout

class MultiWrite(object):
    def __init__(self, *files):
        self.files = files
    def write(self, text):
        for file in self.files:
            file.write(text)
    def close(self):
        for file in self.files:
            file.close()

import sys

# no need to save stdout. There's already a copy in sys.__stdout__.
sys.stdout = MultiWrite(open('file-1', 'w'), open('file-2', 'w'))
print("Hello, World!")

sys.stdout.close()

sys.stdout = sys.__stdout__  #reassign old stdout.

无论如何,我同意阿什维尼的观点。看起来你正在寻找一个黑客来获得一些东西,而你应该真正使用不同的方法。

【讨论】:

    【解决方案2】:

    只需使用file.write:

    with open('FILE.txt','w')  as output_file:
        #do something here
        output_file.write(somedata) # add '\n' for a new line
    
    with open('FILE_APPENDING.txt','a')  as output_file1:
        #do something here
        output_file1.write(somedata) 
    

    关于file.write的帮助:

    >>> print file.write.__doc__
    write(str) -> None.  Write string str to file.
    
    Note that due to buffering, flush() or close() may be needed before
    the file on disk reflects the data written.
    

    【讨论】:

    • 那不允许我将 sys.stdout 文件写入两个地方?
    • @Hyflex 为什么需要使用sys.stdoutfile.write 是更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2015-04-11
    • 2011-01-30
    • 2014-01-05
    • 1970-01-01
    • 2021-10-21
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多