【问题标题】:Command-line autocompletion for python -m modulepython -m 模块的命令行自动完成
【发布时间】:2019-04-15 14:27:15
【问题描述】:

是否有可能获得python -m package.subpackage.module 的命令行自动补全?

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

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

此功能是否内置在某个地方,或者我该如何设置?

【问题讨论】:

  • bash 补全工具是可扩展的。

标签: python bash autocomplete bash-completion


【解决方案1】:

正如评论部分所说,您需要扩展 bash-completion 工具。然后,您将创建一个脚本来处理您需要的情况(即:当最后一个参数是 -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]

Here是一个教程,以这种方式继续。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2021-06-05
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多