Python版本的freopen()
python中有什么东西可以在C或C ++中复制freopen()的function吗? 确切地说,我想复制以下function:
freopen("input.txt","r",stdin);
和
freopen("output.txt","w",stdout);
然后对文件I / O使用相同(标准)的控制台I / O函数。 有任何想法吗?
sys.stdout
只是file
对象,因此,您可以将其重新打开到另一个目标
out = sys.stdout sys.stdout = open('output.txt', 'w') // do some work sys.stdout = out
out
仅用于在下class后将sys.stdout
目标恢复为默认值(如Martijn Pieters建议的那样 – 您可以使用sys.__stdout__
恢复它,或者根本不恢复,如果您不需要它)。
如果您正在使用* nix平台,您可以编写自己的freopen
。
def freopen(f,option,stream): import os oldf = open(f,option) oldfd = oldf.fileno() newfd = stream.fileno() os.close(newfd) os.dup2(oldfd, newfd) import sys freopen("hello","w",sys.stdout) print "world"
您可能还想查看contextmanager
中的contextmanager
装饰器以进行临时重定向:
from contextlib import contextmanager import sys @contextmanager def stdout_redirected(new_stdout): save_stdout = sys.stdout sys.stdout = new_stdout try: yield finally: sys.stdout = save_stdout
例:
with opened(filename, "w") as f: with stdout_redirected(f): print "Hello"
试试这个:
import sys sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w')
文本文件是自我解释的。 您现在可以在Sublime Text或任何其他文本编辑器上运行此代码。
这应该有所帮助:
import sys def freopen(filename, mode): if mode == "r": sys.stdin = open(filename, mode) elif mode == "w": sys.stdout = open(filename, mode) # ---- MAIN ---- freopen("input.txt", "r") freopen("output.txt", "w")