【问题标题】:IPython custom tab-completion for user magic function用于用户魔术功能的 IPython 自定义选项卡完成
【发布时间】:2016-04-07 14:25:52
【问题描述】:

在 IPython 中,为用户定义的对象提供制表符补全相当容易:只需定义一个 __dir__ 方法,该方法将字符串列表返回给对象。

IPython 还为我们提供了一种使用方便的register_line_magic 实用程序来定义我们自己的自定义魔术函数的方法。在某些~/.ipython/profile_default/startup/magictest.py:

from IPython.core.magic import register_line_magic

@register_line_magic
def show(dataType):
    # do something depending on the given `dataType` value

现在我的问题是:如何为这个神奇的功能提供自动完成功能?

根据this email,应该查看IPython.core.interactiveshell.InteractiveShell.init_completer() 以获取诸如%reset、'%cd' 等魔术函数完成器的示例...

但是,在与我的魔术函数定义相同的启动文件中,以下代码不起作用:

from IPython.core.interactiveshell import InteractiveShell

def show_complete():
     return ['dbs', 'databases', 'collections']

InteractiveShell._instance.set_hook(
    'complete_command', show_complete, str_key='%show')

在 IPython shell 中,输入 %show TAB 不会触发任何事情(函数中的打印语句表明该函数甚至没有被调用)。

有人可以指出一些关于如何从 Ipython 启动文件中定义此类用户魔术命令参数完成的文档或示例吗?

谢谢!

【问题讨论】:

    标签: python ipython tab-completion ipython-magic


    【解决方案1】:

    你可以用这个:

    def load_ipython_extension(ipython):
        def apt_completers(self, event):
            """ This should return a list of strings with possible completions.
    
            Note that all the included strings that don't start with event.symbol
            are removed, in order to not confuse readline.
            """
    
            return ['update', 'upgrade', 'install', 'remove']
    
        ipython.set_hook('complete_command', apt_completers, re_key = '%%apt')
    

    %%apt 是神奇的关键字

    【讨论】:

    • 输入 %%apt foo 然后点击 Tab 会产生如下事件:namespace(command='%%apt', line='%%apt foo', symbol='foo', text_until_cursor='%%apt foo')
    • 发送!这对我有用,但是我也总是得到这些完成:and is if not in or - 默认选项?有没有办法压制他们?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2013-02-13
    相关资源
    最近更新 更多