Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default function in python shell [duplicate]

Entering an expression in Python shell outputs the repr() of the expression.

Is it possible to set this default function to some user defined function?

like image 825
Shub Avatar asked Sep 26 '26 01:09

Shub


1 Answers

What you are looking for is 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.

Normal behaviour:

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

then

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

modified behaviour:

>>> datetime.now()
2021-11-25 15:26:14.177267
like image 134
Selcuk Avatar answered Sep 27 '26 14:09

Selcuk