在 Python 3 中打印到混合输出?

Print to mixed outputs in Python 3?

有标准方法可以将程序的 putput 打印到输出文件,如 this。有没有办法将 print 函数用于不同的输出?我明白循环

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')
一旦我们进入 with-“循环”,

只会打印到 out.txt 文件。我怎样才能使用相同的片段来代替

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

请注意 with 之外的 for 循环是进行一些计算的更大程序的一部分。我想打印文件中的数据但同时监视程序的状态(显示在屏幕上)。

您可以通过多种方式做到这一点。不过警告:劫持 stdout 或任何标准描述符绝不是一个好主意。与一般情况一样,您的 logging/printing 应该明确写入的位置。

除此之外,您可以劫持 stdout。虽然这不是最好的方法。

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 

一种更简洁的方法是使用打印的 file 参数:

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)

对于带有循环的代码,您可以随机播放代码以便更长时间地控制描述符,或者完全控制描述符并自行管理它。

控制文件:

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

改组代码以便保留描述符:

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