我知道,如果您要将stdout重定向到文件,可以像这样简单地做到这一点。
sys.stdout = open(fpath, 'w')
但是如何切换回标准输出以在终端上写?
更好的选择是根据需要简单地写入文件。
with open('samplefile.txt', 'w') as sample:
print('write to sample file', file=sample)
print('write to console')
重新分配标准输出将意味着您需要跟踪先前的文件描述符,并在需要向控制台发送文本时将其重新分配。
如果您真的必须重新分配,则可以这样做。
holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')