Python Forum
Redirect to file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Redirect to file (/thread-12406.html)



Redirect to file - vndywarhol - Aug-23-2018

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()



RE: Redirect to file - DeaD_EyE - Aug-23-2018

This happens, because you don't catch any exception while calling func().
You can catch all exceptions and log them to a file.
Instead of overwriting sys.stdout, use the print function.
You can define with file the outputfile which is print using.

def decorator(func):
    def wrapper():
        with open('output', 'w') as fd:
            try:
                result = func()
            except Exception as error:
                print(error, file=fd)
            else:
                print(result, file=fd) 
    return wrapper
To return a value, you have to add after the print in the else block return result