Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Redirect to file
#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


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,412 Jul-05-2023, 12:23 AM
Last Post: Skaperen
  stderr redirect to file fmr300 2 3,728 Apr-03-2021, 01:31 AM
Last Post: fmr300
  Cannot redirect print to a file tester_V 3 2,587 Sep-11-2020, 12:21 AM
Last Post: tester_V
  redirect url_for passing arguments with the url Leon79 1 1,712 Jul-09-2020, 05:20 PM
Last Post: Leon79
  Redirect to __stdout__ fails in IDLE shell Pavel_47 1 2,014 Apr-13-2020, 05:13 PM
Last Post: deanhystad
  Python redirect users to another url after form post blsturgeon 5 19,163 Jun-28-2018, 11:53 PM
Last Post: gontajones
  Script for media content and redirect in to a file puneet102 0 2,400 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