如何在文件和终端之间切换sys.stdout?

问题描述 投票:0回答:1

我知道,如果您要将stdout重定向到文件,可以像这样简单地做到这一点。

sys.stdout = open(fpath, 'w')

但是如何切换回标准输出以在终端上写?

python linux stdout
1个回答
0
投票

更好的选择是根据需要简单地写入文件。

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')
© www.soinside.com 2019 - 2024. All rights reserved.