Line completion with custom commands

This my Answer to the stackoverflow question: Line completion with custom commands:

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.