簡體   English   中英

如何使用stdout將打印消息的內容記錄到兩個文件中

[英]How do I log the contents of print messages to two files with stdout

在尋找一些幫助記錄/保存打印到兩個文件位置的幫助,如下所示,有人知道這樣做的方法嗎?

### 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()

在此先感謝-Hyflex

您可以使用一些寫入多個文件的類來重新分配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.

無論如何,我同意阿什維尼的觀點。 看來您應該真正使用其他方法來搜索黑客,以獲得某些東西。

只需使用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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM