简体   繁体   中英

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

Looking for some help logging/saving the prints to two file locations as seen below, does anyone know a way to do this?

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

Thanks in advance - Hyflex

You can reassign sys.stdout with some class that writes to multiple files:

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.

Anyway, I agree with Ashwini. It seems that you are searching a hack to obtain something, when you should really use a different approach.

Simply use 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) 

help on 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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