Line completion with custom commands

后端 未结 6 985
抹茶落季
抹茶落季 2020-12-23 17:33

my Python program can be launched with a range of different options (or subcommands) like:

$ myProgram doSomething
$ myProgram doSomethingElse
$ myProgram no         


        
相关标签:
6条回答
  • 2020-12-23 17:38

    As mentioned in other answers, in bash this can be done with the bash-builtin complete. Easier than writing a function (as in richq's answer) is using complete's option -W which lets you specify a list of words. In your example this would be:

    complete -W "doSomething doSomethingElse nowDoSomethingDifferent" myProgram
    

    As it is a one-liner you don't have to create a file for this, but you can just put it in your .bashrc.

    0 讨论(0)
  • 2020-12-23 17:45

    If you want your program to select an command line option even though you only used an abbreviated form of this option you should have a look at the optparse module in the standard library.

    0 讨论(0)
  • 2020-12-23 17:49

    If I understand correctly you want line completion on the command line before your python script starts. Then you shouldn't search for a python solution, but look at the shell features.

    If you are using bash you can look at /etc/bash_completion, and at least on debian/ubuntu you should create a file in /etc/bash_completion.d/ that specifies the completions for your program.

    0 讨论(0)
  • 2020-12-23 17:50

    Create a file "myprog-completion.bash" and source it in your .bashrc file. Something like this to get you started...

    _myProgram()
    {
      cur=${COMP_WORDS[COMP_CWORD]}
      case "${cur}" in
        d*) use="doSomething" ;;
        n*) use="nowDoSomethingElse" ;;
      esac
      COMPREPLY=( $( compgen -W "$use" -- $cur ) )
    }
    complete -o default -o nospace -F _myProgram  myProgram
    
    0 讨论(0)
  • 2020-12-23 17:51

    There is the module optcomplete which allows you to write the completion for bash autocompletion in your python program. This is very useful in combination with optparse. You only define your arguments once, add the following to your .bashrc

    complete -F _optcomplete <program>
    

    and all your options will be autocompleted.

    0 讨论(0)
  • 2020-12-23 17:57

    As well as I know, PYTHONSTARTUP is for commands to be executed when the interpreter starts up [1]. rlcompleter is for autocompletion inside your script, if it is using readline library. Something like this:

    $ ./myscript.py
    My Script version 3.1415.
    Enter your commands:
    myscript> B<TAB>egin
    myscript> E<TAB>nd
    

    In your example you want to complete on the shell command line. This autocompletion is a shell feature (either bash or zsh, whatever you use). See, for example, an introduction to bash autocompletion (also part 2). For zsh see, for example this guide.

    0 讨论(0)
提交回复
热议问题