How to configure IPython to execute cell blocks the same way as a plain Python REPL does?

感情迁移 提交于 2019-12-01 06:50:44

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

%config InteractiveShell.ast_node_interactivity='all'

or in your ipython_config.py

c.InteractiveShell.ast_node_interactivity = 'all'

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.


The possible settings for InteractiveShell.ast_node_interactivity are currently

  • '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' would have printed the values of i from both loops.

  • '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': compile everything in 'exec' mode.

  • '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"
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!