Custom tab completion in python argparse

后端 未结 2 900
遥遥无期
遥遥无期 2020-12-23 09:44

How to get shell tab completion cooperating with argparse in a Python script?

#!/usr/bin/env python         


        
2条回答
  •  隐瞒了意图╮
    2020-12-23 10:26

    For auto-complete to work you need a bash function to generate the possible options, and then you need to run complete -F

    The best way of doing this is to have the program generate the completion function based on it's own parsing algorithm to avoid duplication. However, at a quick glance on argparse, I could not find a way to access it's internal structure, but I suggest you look for it.

    Here is a bash function that will do for the above program:

    function _example_auto() {
        local cur=${COMP_WORDS[COMP_CWORD]}
        local prev=${COMP_WORDS[COMP_CWORD-1]}
    
        case "$prev" in
        --optional ) 
            COMPREPLY=( $(compgen -W "foo1 foo2 bar" -- $cur) )
            return 0
            ;;
        *)
            COMPREPLY=( $(compgen -W "--optional spam eggs" -- $cur) )
            return 0
            ;;
        esac
    }
    

提交回复
热议问题