有一些标准方法可以将程序的输出打印到这样的输出文件中。有没有办法将print
函数用于不同的输出?我知道环路
with open('out.txt', 'w') as f:
with redirect_stdout(f):
print('data')
只有当我们输入with
-";循环";。我如何使用相同的代码段来代替
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或任何标准描述符从来都不是一个好主意。一般来说,你的日志记录/打印应该明确地写在哪里。
这样一来,你就可以劫持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