2

In Python, overriding sys.excepthook makes it possible to modify what is printed to stderr when there is an exception:

>>> import sys >>> sys.excepthook = lambda _, x, __: print('ERROR:', x) >>> a ERROR: name 'a' is not defined 

I'm looking for a similar functionality for stdout also. Is it possible to do this in Python?

>>> type(5) <class 'int'> >>> # some magical operations >>> type(5) <sinif 'tamsayi'> 

Here <sinif 'tamsayi'> is translation of original output to Turkish. This is just an example and I'm not trying to modify type's output specifically. I'm looking for a way to inspect what is going to written to stdout and modify it according to my needs just like in the case of what I've shown for stderr.

5
  • 2
    Have you looked at docs.python.org/3/library/…? Commented Jan 8, 2021 at 10:14
  • Why don't you just use a logger? Commented Jan 8, 2021 at 10:15
  • 1
    @jonrsharpe Looks relevant, I will check. Commented Jan 8, 2021 at 10:20
  • You can reassign sys.stdout to any file-like object. The original stdout will be kept in sys.__stdout__. Commented Jan 8, 2021 at 10:21
  • 2
    @Qiu I should have checked the sys before asking this. Just by looking at the name I can say that this is what I'm looking for most probably. Commented Jan 8, 2021 at 10:22

1 Answer 1

1

You're probably looking for sys.displayhook:

import sys def my_output(x): #some magical operations sys.displayhook = my_output 
Sign up to request clarification or add additional context in comments.

1 Comment

sys.excepthook for showing exceptions and sys.displayhook for displaying other things :D Super intuitive! Thanks for the answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.