Is it possible to modify what is printed to stdout in Python?

Viewed 112

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.

1 Answers

You're probably looking for sys.displayhook:

import sys    

def my_output(x):
    #some magical operations

sys.displayhook = my_output
Related