【问题标题】:Print to mixed outputs in Python 3?在 Python 3 中打印到混合输出?
【发布时间】:2021-05-17 10:39:27
【问题描述】:

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

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

只有在我们进入with-“循环”后才会打印到 out.txt 文件。我怎样才能使用相同的sn-p来代替

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,只需使用write 等文件方法写入文件和print 打印到屏幕/标准输出。另一种选择是使用print 函数的file 参数写入文件。
  • 听起来你想要一个日志框架,也许吧? Logging HOWTO

标签: python io


【解决方案1】:

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

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

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

【讨论】:

  • 啊废话,我应该写 with 在循环中。
  • 您可以编辑您的问题以使其更准确。 @user2820579
猜你喜欢
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 2019-02-24
  • 2016-04-29
  • 1970-01-01
  • 2020-02-29
相关资源
最近更新 更多