如何配置IPython以像普通的Python REPL一样执行单元块? [英] How to configure IPython to execute cell blocks the same way as a plain Python REPL does?

查看:62
本文介绍了如何配置IPython以像普通的Python REPL一样执行单元块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vanilla Python REPL:

Vanilla Python REPL:

>>> 'na'
'na'
>>> for i in range(4):
...     f'{_+_}'
... else:
...     'batman'
... 
'nana'
'nananana'
'nananananananana'
'nananananananananananananananana'
'batman'
>>> 

具有相同解释器的IPython REPL:

IPython REPL with same interpreter:

>>> 'na'
'na'
>>> for i in range(4): 
...     f'{_+_}' 
... else: 
...     'batman' 
...
>>> _
'na'

这种差异是显然与IPython编译代码的方式有关,而与

This difference is apparently related to the mode in which IPython compiles code, and unrelated to the display hook. Is it possible to configure IPython to compile/exec cell blocks as a plain Python REPL does? I'd prefer if IPython would not interfere or modify such underlying runtime machinery.

推荐答案

设置

Set the InteractiveShell.ast_node_interactivity setting to 'all', either through the %config magic command:

%config InteractiveShell.ast_node_interactivity='all'

或您的ipython_config.py

c.InteractiveShell.ast_node_interactivity = 'all'

这将导致IPython以'single'模式(触发sys.displayhook的模式)而不是不使用sys.displayhook'exec'模式编译所有内容.

This will cause IPython to compile everything in 'single' mode, the mode that triggers sys.displayhook, instead of 'exec' mode, which doesn't use sys.displayhook.

InteractiveShell.ast_node_interactivity的可能设置当前为

  • 'all':在'single'模式下编译所有内容.
  • 'last':以'single'模式编译单元格的最后一个(简单或复合)语句.在类似

  • 'all': compile everything in 'single' mode.
  • 'last': compile the last (simple or compound) statement of a cell in 'single' mode. Differs from 'all' in cases like

In [7]: for i in range(5):
   ...:     i
   ...: for i in range(3):
   ...:     i
   ...:     
Out[7]: 0
Out[7]: 1
Out[7]: 2

'all'将从两个循环中打印i的值.

'all' would have printed the values of i from both loops.

'last_expr':如果该语句是表达式语句,则以'single'模式编译单元格的最后一条语句.这是IPython的默认设置.

'last_expr': compile the last statement of a cell in 'single' mode if that statement is an expression statement. This is IPython's default.

'none':以'exec'模式编译所有内容.

'none': compile everything in 'exec' mode.

'last_expr_or_assign':与'last_expr'类似,但是如果最后一条语句是赋值语句,则执行其他一些AST转换以打印所赋值:

'last_expr_or_assign': like 'last_expr', but does some additional AST transformation to print the value assigned if the last statement is an assignment statement:

In [2]: xyz = "something else"
Out[2]: "something else"

这篇关于如何配置IPython以像普通的Python REPL一样执行单元块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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