为什么键入变量(或表达式)将值打印到stdout? [英] Why does typing a variable (or expression) print the value to stdout?

查看:64
本文介绍了为什么键入变量(或表达式)将值打印到stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个例子为例:

>>> 5+10
15
>>> a = 5 + 10
>>> a
15

Python如何以及为什么在没有显式print语句的情况下执行此操作?

How and why does Python do this without an explicit print statement?

如果我在 IPython 单元格中执行相同的操作,则实际上最后一个这样的值是以这种方式在stdout上打印:

If I do the same thing in an IPython cell, only the last such value is actually printed on stdout in this way:

In[1]: 5+10
       1

Out[1]: 1

为什么会这样?

推荐答案

当Python处于交互式"状态时,模式,它启用非交互模式下没有的某些行为.例如,最初在 sys.displayhook ="https://www.python.org/dev/peps/pep-0217/" rel ="noreferrer"> PEP 217 .

When Python is in "interactive" mode, it enables certain behaviors it doesn't have in non-interactive mode. For example, sys.displayhook, originally specified in PEP 217.

如果值不为None,则此函数将其打印到sys.stdout,并将其保存在__builtin__._中.

sys.displayhook.

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

在默认的Python版本中,sys.displayhook

In the default Python repl, sys.displayhook is

>>> import sys;
>>> sys.displayhook
<built-in function displayhook>

但是在IPython中是

but in IPython it's

In [1]: import sys

In [2]: sys.displayhook
Out[2]: <IPython.terminal.prompts.RichPromptDisplayHook at 0x7f630717fa58>

这就是为什么您看到Python和IPython之间行为不同的原因.

So that's why you see different behavior between Python and IPython.

这篇关于为什么键入变量(或表达式)将值打印到stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆