我怎么能告诉我的 Python 脚本参数的 bash 有效的制表符补全

13 bash autocomplete

假设我有一个程序 hello.py 并且它的一个可能的有效参数是:

./hello.py autoawesomesauce
Run Code Online (Sandbox Code Playgroud)

是否可以输入:

./hello.py auto[tab]
Run Code Online (Sandbox Code Playgroud)

在这一点上,部分完成的参数被发送到 hello,它识别它,然后在 shell 上完成它:

./hello.py autoawesomesauce
Run Code Online (Sandbox Code Playgroud)

我知道 git 会做这样的事情,但是可以为 Python 脚本 + Bash 做吗?

Bil*_*nch 7

在 Linux 系统上,您通常可以在以下位置找到大量示例脚本:/etc/bash_completion.d. 如果您获取这些脚本,那么您将获得自动完成行为。

我已经包含了该目录中的一个示例。这是 unrar 的完成脚本。

_unrar()
{
    local cur

    COMPREPLY=()
    _get_comp_words_by_ref cur

    if [[ "$cur" == -* ]] ; then
        COMPREPLY=( $( compgen -W '-ad -ap -av- -c- -cfg- -cl -cu \
            -dh -ep -f -idp -ierr -inul -kb -o+ -o- -ow -p -p- -r -ta \
            -tb -tn -to -u -v -ver -vp -x -x@ -y' -- "$cur" ) )
    else
        if [ $COMP_CWORD -eq 1 ]; then
            COMPREPLY=( $( compgen -W 'e l lb lt p t v vb vt x' -- "$cur" ) )
        else
            _filedir '@(rar|RAR)'
        fi
    fi

} &&
complete -F _unrar -o filenames unrar
Run Code Online (Sandbox Code Playgroud)


小智 4

此功能与 Python 无关。这是底层 shell 的纯粹功能。因此,请阅读有关自动完成的 bash 文档。

谷歌搜索“bash auto-completion”,你会在前 10 个点击中找到至少 5 个合理的文档。