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


Messages In This Thread
Redirect to file - by vndywarhol - Aug-23-2018, 10:40 AM
RE: Redirect to file - by DeaD_EyE - Aug-23-2018, 11:01 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  redirect STDIO in the Python code Skaperen 6 1,357 Jul-05-2023, 12:23 AM
Last Post: Skaperen
  stderr redirect to file fmr300 2 3,658 Apr-03-2021, 01:31 AM
Last Post: fmr300
  Cannot redirect print to a file tester_V 3 2,556 Sep-11-2020, 12:21 AM
Last Post: tester_V
  redirect url_for passing arguments with the url Leon79 1 1,685 Jul-09-2020, 05:20 PM
Last Post: Leon79
  Redirect to __stdout__ fails in IDLE shell Pavel_47 1 1,986 Apr-13-2020, 05:13 PM
Last Post: deanhystad
  Python redirect users to another url after form post blsturgeon 5 19,006 Jun-28-2018, 11:53 PM
Last Post: gontajones
  Script for media content and redirect in to a file puneet102 0 2,373 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