繁体   English   中英

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

[英]Print to mixed outputs in Python 3?

有一些标准方法可以将程序的 putput 打印到 output 文件,如下所示 有没有办法将print function 用于不同的输出? 我明白循环

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

只有在我们输入with -"loop" 后才会打印到 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循环是进行一些计算的更大程序的一部分。 我想打印文件中的数据,但同时监视程序的状态(显示在屏幕上)。

您可以通过多种方式做到这一点。 但警告:劫持标准输出或任何标准描述符绝不是一个好主意。 与一般情况一样,您的日志记录/打印应该在写入的位置明确。

这样一来,您就可以劫持标准输出。 虽然同样,这不是最好的方法。

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 

一种更简洁的方法是使用 print 的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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