[英]How do I log the contents of print messages to two files with stdout
在寻找一些帮助记录/保存打印到两个文件位置的帮助,如下所示,有人知道这样做的方法吗?
### Create output file/open it for editing
output_file = open('FILE.txt','w')
output_file1 = open('FILE_APPENDING.txt','a')
## Create a backup of current setting
old_stdout = sys.stdout
sys.stdout = output_file
sys.stdout = output_file1
print "stuff here"
## loop here printing stuff
## Revert python to show prints as normal
sys.stdout=old_stdout
## Close the file we are writing too
output_file.close()
output_file1.close()
在此先感谢-Hyflex
您可以使用一些写入多个文件的类来重新分配sys.stdout
:
class MultiWrite(object):
def __init__(self, *files):
self.files = files
def write(self, text):
for file in self.files:
file.write(text)
def close(self):
for file in self.files:
file.close()
import sys
# no need to save stdout. There's already a copy in sys.__stdout__.
sys.stdout = MultiWrite(open('file-1', 'w'), open('file-2', 'w'))
print("Hello, World!")
sys.stdout.close()
sys.stdout = sys.__stdout__ #reassign old stdout.
无论如何,我同意阿什维尼的观点。 看来您应该真正使用其他方法来搜索黑客,以获得某些东西。
只需使用file.write
:
with open('FILE.txt','w') as output_file:
#do something here
output_file.write(somedata) # add '\n' for a new line
with open('FILE_APPENDING.txt','a') as output_file1:
#do something here
output_file1.write(somedata)
关于file.write
帮助:
>>> print file.write.__doc__
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.