Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Redirect to file
#1
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()
Reply
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  redirect STDIO in the Python code Skaperen 6 1,302 Jul-05-2023, 12:23 AM
Last Post: Skaperen
  stderr redirect to file fmr300 2 3,598 Apr-03-2021, 01:31 AM
Last Post: fmr300
  Cannot redirect print to a file tester_V 3 2,529 Sep-11-2020, 12:21 AM
Last Post: tester_V
  redirect url_for passing arguments with the url Leon79 1 1,658 Jul-09-2020, 05:20 PM
Last Post: Leon79
  Redirect to __stdout__ fails in IDLE shell Pavel_47 1 1,970 Apr-13-2020, 05:13 PM
Last Post: deanhystad
  Python redirect users to another url after form post blsturgeon 5 18,886 Jun-28-2018, 11:53 PM
Last Post: gontajones
  Script for media content and redirect in to a file puneet102 0 2,355 May-22-2018, 12:06 PM
Last Post: puneet102

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020