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(\
This should help:
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")
You may also want to look at the contextmanager decorator in contextlib for temporary redirection:
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
Example:
with open(filename, "w") as f:
with stdout_redirected(f):
print "Hello"
If you're working on *nix platform, you can write your own 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"
Try this:
import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
Text files are self explanatory. You can now run this code on Sublime Text or any other text editor.
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
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).