【问题标题】:Override ipython exit function - or add hooks in to it覆盖 ipython 退出函数 - 或在其中添加挂钩
【发布时间】:2016-09-14 21:16:03
【问题描述】:

在我的项目 manage 中,我正在嵌入 iPython:

from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = "Welcome to my shell"
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
start_ipython(argv=[], user_ns={}, config=c)

它运行良好并打开了我的 iPython 控制台,但要离开 ipython,我只需键入 exitexit() 或按 ctrl+D

我想做的是添加一个exit hook 或用其他东西替换那个exit 命令。

假设我有一个函数。

def teardown_my_shell():
    # things I want to happen when iPython exits

当我exit 时如何注册要执行的函数,甚至如何让exit 执行该函数?

注意:我尝试通过 user_ns={'exit': teardown_my_shell} 并不起作用。

谢谢。

【问题讨论】:

    标签: python shell ipython


    【解决方案1】:

    首先感谢@user2357112,我学会了如何创建扩展和注册钩子,但我发现shutdown_hook已被弃用。

    正确的方法很简单。

    import atexit
    
    def teardown_my_shell():
        # things I want to happen when iPython exits
    
    atexit.register(teardown_my_shell)
    

    【讨论】:

      【解决方案2】:

      谷歌搜索IPython exit hook 出现IPython.core.hooks。从该文档中,您可以在 IPython extension 中定义一个退出钩子并将其注册到 IPython 实例的 set_hook 方法中:

      # whateveryoucallyourextension.py
      
      import IPython.core.error
      
      def shutdown_hook(ipython):
          do_whatever()
          raise IPython.core.error.TryNext
      
      def load_ipython_extension(ipython)
          ipython.set_hook('shutdown_hook', shutdown_hook)
      

      您必须将扩展程序添加到您的c.InteractiveShellApp.extensions

      【讨论】:

      • 注册扩展的方法可行,但我发现shutdown_hook已被弃用,我将把解决方案作为答案
      • @rochacbruno:嗯。这不在我找到的文档中,但谷歌建议你是对的。我认为 shutdown_hook 是为了当你想在 IPython 实例关闭时做某事,但 Python 解释器本身可能仍然保持活动状态。
      • 这似乎已被弃用:UserWarning: Hook shutdown_hook is deprecated. Use the atexit module instead.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 2018-10-09
      • 2011-02-08
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多