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

时间:2018-11-12 20:13:01

标签: python bash autocomplete bash-completion

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

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

我希望能够进行subpackage并自动完成对library(dplyr) library(sparklyr) config <- spark_config() config$spark.driver.memory <- "8G" config$spark.executor.memory <- "8G" config$spark.executor.executor <- "2" config$spark.executor.cores <- "4" config$spark.kryoserializer.buffer.max <- "2000m" config$spark.driver.maxResultSize <- "4G" config$spark.akka.frameSize <- "768" sc <- spark_connect(master="yarn-client", version="2.2.0", config=config, spark_home = '/opt/cloudera/parcels/SPARK2-2.2.0.cloudera1-1.cdh5.12.0.p0.142354/lib/spark2') 的填写。

此功能是内置于某处还是如何设置?

1 个答案:

答案 0 :(得分: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是以这种方式继续的教程。