繁体   English   中英

用户魔术功能的IPython自定义制表符完成

[英]IPython custom tab-completion for user magic function

在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启动文件中定义此类用户魔术命令参数完成情况吗?

谢谢!

您可以使用此:

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是魔术关键字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM