我正在使用上下文管理器來包裝將顯示在終端中並同時寫入文件的文本。文件中的上下文管理器I/O操作
我面對這個問題,並得到了解決,請 Writing terminal output to terminal and to a file?
無法更改的問題是功能(等FUNC1和FUNC2)的「與」陳述的任何輸出作爲sys.stdout.write函數的表演過後值錯誤:在關閉的文件I/O操作
示例代碼:
import sys, datetime
class FileWrite(object):
def __init__(self,log_file_name, stdout):
self.log_file_name = log_file_name
self.stdout = stdout
def __enter__(self):
self.log_file = open(self.log_file_name, 'a', 0)
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.log_file.close()
def write(self, data):
self.log_file.write(data)
self.stdout.write(data)
self.stdout.flush()
def func1():
sys.stdout.write('A')
def func2():
sys.stdout.write('B')
def main():
with FileWrite(..........., sys.stdout) as sys.stdout:
func1()
func2()
sys.stdout.write('test')
main()
............................
# both output A and B is showing in terminal and writing in file
............................
# writing 'test' only in terminal......
I/O operation in closed file
你能舉個例子嗎 – mortuzahasan
這個工作適合你嗎? –
是的。它不寫入文件,而'做一些寫作' – mortuzahasan