代码之家  ›  专栏  ›  技术社区  ›  Hatshepsut

python-m模块的命令行自动完成

  •  0
  • Hatshepsut  · 技术社区  · 7 年前

    是否可以通过命令行自动完成 python -m package.subpackage.module ?

    python ./package/subpackage/module.py ,它会自动完成目录和文件路径。但是 -m ,python将库的模块作为脚本运行,并具有适当的名称空间和导入路径。

    我希望能够 python -m package.s[TAB] 自动补全到 subpackage .

    这个功能是内置的吗?或者我如何设置它?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Amessihel    7 年前

    如评论部分所述,您需要扩展 -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 是以这种方式继续的教程。