简体   繁体   中英

Print to mixed outputs in Python 3?

There are standard methods to print the putput of a program to an output file like this . Is there a way to use the print function for different outputs? I understand that the loop

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

only prints to the out.txt file once we enter the with -"loop". How can I use the same snippet to do instead

for i in range(isteps):
    # Do something with the program 
    with open('out.txt', 'w') as f:
        with redirect_stdout(f):
            print('data') # Writes in out.txt
            print1('Status') # Writes on the screen

Note that the for loop outside the with 's is part of a bigger program that makes some computation. I would like to print the data in the file but at the same time monitor the status of the program (displayed on the screen).

You can do this in many ways. Warning though: it's never a good idea to hijack stdout or any standard descriptors. As well as just in general your logging/printing should be explicit in where it's writing to.

With that out the way, you could hijack stdout. Although again, this is not the best approach.

import sys

print('This message will be displayed on the screen.')

original_stdout = sys.stdout # Save a reference to the original standard output

with open('filename.txt', 'w') as f:
    sys.stdout = f # Change the standard output to the file we created.
    print('This message will be written to a file.')
    sys.stdout = original_stdout # Reset the standard output to its original value 

A somewhat cleaner way would be to use the file parameter of print:

import sys

print('This message will be displayed on the screen.')

with open('filename.txt', 'w') as f:
    print('This message will be written to a file.', file=f)

For your code with the loop you can either shuffle the code around so you can keep a handle on the descriptor for longer or take full control of the descriptor and manage it yourself.

taking control of the file:

isteps = 4

f = open('out.txt', 'w')  # since we moved this out of a with we need to manage the discriptor
for i in range(isteps):
    # Do something with the program 
    print('data', file=f) # Writes in out.txt
    print('Status') # Writes on the screen
f.close()

shuffling the code around so you keep the descriptor:

with open('out.txt', 'w') as f:  # No need to manage since we have the with
    for i in range(isteps):
        # Do something with the program
        print('data', file=f) # Writes in out.txt
        print('Status') # Writes on the screen

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