【问题标题】:Why doesn't QtConsole echo next()?为什么 QtConsole 不回显 next()?
【发布时间】:2016-12-28 08:01:35
【问题描述】:

我发现了这个关于 Python 中迭代器行为的问题:

Python list iterator behavior and next(iterator)

当我输入代码时:

a = iter(list(range(10)))
for i in a:
    print a
    next(a)

进入它返回的jupyter-qtconsole

0
2
4
6
8

正如 Martijn Pieters 所说,当解释器没有回应对 next(a) 的调用时应该这样做。

但是,当我在 Bash 解释器和 IDLE 中再次运行相同的代码时,打印的代码:

0
1
2
3
4
5
6
7
8
9

到控制台。

我运行了代码:

import platform
platform.python_implementation()

在所有三个环境中,他们都说我跑了'CPython'

那么为什么 QtConsole 会抑制 next(a) 调用,而 IDLE 和 Bash 不会呢?

如果有帮助,我将在 Mac OSX 上运行 Python 2.7.9 并使用 Anaconda 发行版。

【问题讨论】:

    标签: python interpreter jupyter python-internals


    【解决方案1】:

    这只是IPythonQtConsole 的基础)的开发人员就应该回显给用户的内容做出的选择。

    具体来说,在使用的InteractiveShell 类中,函数run_ast_nodes 默认使用interactivity='last_expr' 定义。该属性的文档说明:

    interactivity : str
      'all', 'last', 'last_expr' or 'none', specifying which nodes should be
      run interactively (displaying output from expressions). 'last_expr'
      will run the last node interactively only if it is an expression (i.e.
      expressions in loops or other blocks are not displayed. Other values
      for this parameter will raise a ValueError.
    

    如您所见:循环或其他块中的表达式不显示

    如果你真的需要,你可以在 IPython 的配置文件中更改它,让它像你的 repl 一样工作。关键是,这只是设计师的偏好。

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2012-12-03
      • 2020-09-25
      • 2016-12-13
      • 2021-07-15
      • 2012-11-24
      • 2021-08-18
      • 1970-01-01
      • 2011-04-07
      相关资源
      最近更新 更多