Is it possible to acces stdout via regular open/write in Python
I am trying to create a scipr which would enable either writing on stdout or in file. Is it somehow possible to write to each via the same开发者_如何学Python snippet instead of using print for stdou and io.write() for files?
Examples of both:
out_file = open("test.txt", "wt")
out_file.write("Text")
out_file.close()
and
print("Text", file=sys.stdout)
is this what you want?
from __future__ import print_function, with_statement
def my_print(text, output):
if type(output) == str:
with open(output, 'w') as output_file:
print(text, file=output_file)
elif type(output) == file:
print(text, file=output)
else:
raise IOError
I think I understand, maybe this:
from __future__ import print_function, with_statement
def my_print(text, output):
if type(output) == str:
try:
output_file = eval(output)
assert type(output_file) == file
except (NameError, AssertionError):
output_file = open(output, 'w')
print(text, file=output_file)
output_file.close()
elif type(output) == file:
print(text, file=output)
else:
raise IOError
with this you can pass the string 'sys.stdout' to the function and it will first try to take it as a file (from system or previously opened), if it raises a NameError, it opens it as a new file
精彩评论