Aug-23-2018, 10:40 AM
I would like to redirect all the function outputs and errors to a separate file using the context manager. I wrote the code for a function that executes without errors. It works perfectly.
import sys
def decorator(func):
def wrapper():
with open('output', 'w') as f:
# sys.stderr = f
sys.stdout = f
print(func())
return wrapper
# @decorator
# def function_with_exc():
# return 5 / 0
@decorator
def function_without_exc():
return 5 * 2
# function_with_exc()
function_without_exc()But when I try to do the same for outputting errors, nothing is stored in the file, why?import sys
def decorator(func):
def wrapper():
with open('output', 'w') as f:
sys.stderr = f
# sys.stdout = f
print(func())
return wrapper
@decorator
def function_with_exc():
return 5 / 0
# @decorator
# def function_without_exc():
# return 5 * 2
function_with_exc()
# function_without_exc()
