繁体   English   中英

python -m模块的命令行自动补全

[英]Command-line autocompletion for python -m module

是否可以获取python -m package.subpackage.module命令行自动完成功能?

这与python ./package/subpackage/module.py类似但不相同,它会自动完成目录和文件路径。 但是,使用-m ,python将使用适当的命名空间和导入路径将库的模块作为脚本运行。

我希望能够执行python -m package.s[TAB]并自动完成subpackage

此功能内置在某个地方吗,或者如何设置?

如评论部分所述,您需要扩展bash补全工具。 然后,您将创建一个脚本来处理所需的情况(即:当最后一个参数是-m )。

下面的这个小示例显示了自定义完成脚本的开始。 我们将其命名为python_completion.sh

_python_target() {
    local cur prev opts

    # Retrieving the current typed argument
    cur="${COMP_WORDS[COMP_CWORD]}"

    # Retrieving the previous typed argument ("-m" for example)
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Preparing an array to store available list for completions
    # COMREPLY will be checked to suggest the list
    COMPREPLY=()

    # Here, we'll only handle the case of "-m"
    # Hence, the classic autocompletion is disabled
    # (ie COMREPLY stays an empty array)
    if [[ "$prev" != "-m" ]]
    then
        return 0
    fi

    # Retrieving paths and converts their separators into dots
    # (if packages doesn't exist, same thing, empty array)
    if [[ ! -e "./package" ]]
    then
       return 0
    fi

    # Otherwise, we retrieve first the paths starting with "./package"
    # and converts their separators into dots
    opts="$(find ./package -type d | sed -e 's+/+.+g' -e 's/^\.//' | head)"

    # We store the whole list by invoking "compgen" and filling
    # COMREPLY with its output content.
    COMPREPLY=($(compgen -W "$opts" -- "$cur"))

}

complete -F _python_target python

(警告。此脚本有一个缺陷,不适用于包含空格的文件名) 要对其进行测试,请在当前环境中运行它:

. ./python_completion.sh

并测试一下:

python -m packag[TAB]

是以这种方式继续的教程。

暂无
暂无

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

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