I'm writing a CLI application using the python click library, and I want users of my CLI to have shell autocompletion out of the box. Precisely, I want my users to install my CLI using pip install my-cli and after that they would have autocompletion already without having to source any shell file or install any other package.
I already implemented the autocompletion script as shown in the official docs of the click library and automated the autocompletion installation in setup.py. I did it following these instructions
However, in this case, my users would have to install my-cli and then re-source the shell script file (e.g .bashrc for bash).
Precisely, this is what is happening:
- open the terminal
- run
pip install my-cli(I automated installing the completion script here) - users do not have autocompletion yet. Therefore, they should open a new terminal or run
source .bashrc(this is the step that I want to automate, if possible) - After that, autocompletion works fine
I don't know if this is possible in my case. I know that I can't source a shell script using python since the python subprocess module will spawn a subprocess and the environment changes will not apply on the current process in this case (correct me if I'm wrong).
On the other way, some packages like git and docker provide autocompletion automatically after installing them. Last time I installed docker and then run docker <Tab> <Tab> I already got a list of the subcommands that I can use. So it would be interesting to know how to achieve this using python.
Interestingly, some other python CLI frameworks like typer provides a way to automatically install autocompletion using a subcommand. However, after running the install command, it shows a message that you should re-source the bash script or open a new terminal in order to get autocompletion, which makes me wonder if it's possible to automate this step, because I'm sure they would have done it if that is the case.