为什么键入变量(或表达式)会将值打印到标准输出?
Why does typing a variable (or expression) print the value to stdout?
举个例子:
>>> 5+10
15
>>> a = 5 + 10
>>> a
15
Python 如何以及为什么在没有显式打印语句的情况下执行此操作?
如果我在 IPython 单元格中做同样的事情,只有最后一个这样的值实际上以这种方式打印在标准输出上:
In[1]: 5+10
1
Out[1]: 1
为什么会这样?
这就是所有口译员的工作方式。他们不需要任何 print
,但有一件事,没有 print
他们会做所有事情的 repr
,而 print
则不需要,例如:
>>> 'blah'
'blah'
>>> print('blah')
blah
>>>
看看引号。
另请参阅:
>>> print(repr('blah'))
'blah'
>>>
repr
也一样。
当 Python 处于“交互”模式时,它会启用某些在非交互模式下没有的行为。例如,sys.displayhook
, originally specified in PEP 217.
If value is not None, this function prints it to sys.stdout, and saves it in __builtin__._
.
sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.
您可以修改此行为:
>>> import sys
>>> def shook(expr):
... print(f'can haz {expr}?')
...
>>> sys.displayhook = shook
>>> 123
can haz 123?
>>> False
can haz False?
>>> None
can haz None?
并将其恢复正常:
>>> sys.displayhook = sys.__displayhook__
>>> 3
3
在默认的Pythonrepl中,sys.displayhook
是
>>> import sys;
>>> sys.displayhook
<built-in function displayhook>
但在 IPython 中是
In [1]: import sys
In [2]: sys.displayhook
Out[2]: <IPython.terminal.prompts.RichPromptDisplayHook at 0x7f630717fa58>
这就是为什么您会看到 Python 和 IPython 之间的不同行为。
举个例子:
>>> 5+10
15
>>> a = 5 + 10
>>> a
15
Python 如何以及为什么在没有显式打印语句的情况下执行此操作?
如果我在 IPython 单元格中做同样的事情,只有最后一个这样的值实际上以这种方式打印在标准输出上:
In[1]: 5+10
1
Out[1]: 1
为什么会这样?
这就是所有口译员的工作方式。他们不需要任何 print
,但有一件事,没有 print
他们会做所有事情的 repr
,而 print
则不需要,例如:
>>> 'blah'
'blah'
>>> print('blah')
blah
>>>
看看引号。
另请参阅:
>>> print(repr('blah'))
'blah'
>>>
repr
也一样。
当 Python 处于“交互”模式时,它会启用某些在非交互模式下没有的行为。例如,sys.displayhook
, originally specified in PEP 217.
If value is not None, this function prints it to sys.stdout, and saves it in
__builtin__._
.sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.
您可以修改此行为:
>>> import sys
>>> def shook(expr):
... print(f'can haz {expr}?')
...
>>> sys.displayhook = shook
>>> 123
can haz 123?
>>> False
can haz False?
>>> None
can haz None?
并将其恢复正常:
>>> sys.displayhook = sys.__displayhook__
>>> 3
3
在默认的Pythonrepl中,sys.displayhook
是
>>> import sys;
>>> sys.displayhook
<built-in function displayhook>
但在 IPython 中是
In [1]: import sys
In [2]: sys.displayhook
Out[2]: <IPython.terminal.prompts.RichPromptDisplayHook at 0x7f630717fa58>
这就是为什么您会看到 Python 和 IPython 之间的不同行为。