Line completion with custom commands

柔情痞子 提交于 2019-11-29 21:32:29

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

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.

Scz

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!