[英]IPython and REPL behave differently when displaying data without the print function
Note that all experiments have been performed on Python3.4.3 and IPython 5.1.0 (for python3). 请注意,所有实验都是在Python3.4.3和IPython 5.1.0(对于python3)上进行的。
Consider a function that returns the identity: 考虑一个返回标识的函数:
def my_func():
return 1
Now, this function is called from a loop inside a REPL session. 现在,从REPL会话内的循环调用此函数。
for _ in range(3):
my_func()
On, IPython, nothing is displayed. 在,IPython,没有显示任何内容。
In [96]: for _ in range(3):
...: my_func()
...:
In [97]:
But, on the REPL, something is: 但是,在REPL上,有些东西是:
>>> for _ in range(3):
... my_func()
...
1
1
1
>>>
Is it because of something IPython does? 是因为IPython的事情吗? I've examined the bytecode and in either case, they're identical.
我检查了字节码,在任何一种情况下,它们都是相同的。 So, it has nothing to do with the bytecode generation but rather with how it is interpreted in either case.
因此,它与字节码生成无关,而是与两种情况下的解释方式无关。
For how it works, IPython compiles loops in 'exec'
mode instead of 'single'
, so sys.displayhook
is not triggered for expression statements inside a loop. 对于它的工作方式, IPython以
'exec'
模式而不是'single'
编译循环 ,因此不会为循环内的表达式语句触发sys.displayhook
。 The regular interactive interpreter executes anything you enter in 'single'
mode. 常规交互式解释器执行您在
'single'
模式下输入的任何内容。 'single'
mode is the mode where expression statements trigger sys.displayhook
. 'single'
模式是表达式语句触发sys.displayhook
的模式。
For why IPython does this, the regular Python behavior is more annoying than useful. 为什么IPython这样做,常规的Python行为比使用更烦人。 You rarely want to auto-print the values of expression statements in a loop;
您很少想在循环中自动打印表达式语句的值; more frequently, it'll happen by accident and scroll things you're interested in off the screen.
更常见的是,它会偶然发生,并在屏幕上滚动您感兴趣的内容。
IPython tries to provide more useful behavior. IPython试图提供更有用的行为。 It's much more intuitive to explicitly print the things you want printed than to explicitly suppress the things you don't want printed.
明确打印您想要打印的内容比明确禁止您不想打印的内容要直观得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.