3

在 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

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

根据这封电子邮件,应该查看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 启动文件中定义此类用户魔术命令参数完成的文档或示例吗?

谢谢!

4

1 回答 1

4

你可以使用这个:

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 是神奇的关键字

于 2017-01-19T08:58:17.573 回答