是否可以修改 Python 中打印到标准输出的内容?

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

在Python中,覆盖sys.excepthook可以在出现异常时修改打印到stderr的内容:

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

我也在寻找 stdout 的类似功能。是否可以在 Python 中执行此操作?

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

这里 <sinif 'tamsayi'> 是将原始输出翻译成土耳其语。这只是一个示例,我并不是要专门修改 type 的输出。我正在寻找一种方法来检查将要写入 stdout 的内容并根据我的需要对其进行修改,就像我为 stderr.

显示的内容一样

您可能正在寻找 sys.displayhook:

import sys    

def my_output(x):
    #some magical operations

sys.displayhook = my_output