python shell 中的默认函数

Default function in python shell

在 Python 中输入表达式 shell 输出表达式的 repr()

是否可以将此默认函数设置为某些用户定义的函数?

你要找的是sys.displayhook:

sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook.

正常行为:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2021, 11, 25, 15, 26, 1, 772968)

然后

>>> import sys
>>> def new_hook(value):
...   sys.stdout.write(str(value))
...   sys.stdout.write("\n")
... 
>>> sys.displayhook = new_hook

修改后的行为:

>>> datetime.now()
2021-11-25 15:26:14.177267