freopen函数的Python版本() [英] Python version of freopen()
问题描述
有没有在Python任何可以复制的freopen函数()C或C ++的功能?要precise,我想复制的功能:
Is there anything in python that can replicate the functionality of freopen() in C or C++? To be precise, I want to replicate the functionality of:
freopen("input.txt","r",stdin);
和
freopen("output.txt","w",stdout);
然后使用相同的(标准)功能控制台I / O的文件I / O。任何想法?
And then use the same (standard) functions for console I/O for file I/O. Any ideas?
推荐答案
为sys.stderr
简直就是文件
对象,因此,您可以将其重新打开到另一个目的地
sys.stdout
is simply file
object, so, you can reopen it to another destination
out = sys.stdout
sys.stdout = open('output.txt', 'w')
// do some work
sys.stdout = out
退出
仅用于恢复为sys.stderr
目的地下班后默认(所建议的Martijn Pieters的 - 你可以通过使用 SYS .__标准输出__
,或无法收回所有,如果你不需要它)。
out
is only for recovering sys.stdout
destination to default after work (as suggested Martijn Pieters - you can recover it by using sys.__stdout__
, or not recover at all, if you don't need it).
这篇关于freopen函数的Python版本()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!