3 Steps to Make a Professional CLI Tool Using Python’s Click

With 3 easy steps, you can make your CLI tool clean and professional.
The Problem
I started to create a CLI tool that I was pretty excited about using the Click library for Python. It felt good to get my tool in my computer’s path and be able to run my script with my command prompts. Everything was all fine except that my CLI tool looked like an amateur had written it. My problem was that calling my CLI tool looked like:
$ python mysupercoolscript.py useful_command
when I really wanted it to look like:
$ mysupercoolscript useful_command
Much nicer. Cleaner. Professional. Not to mention I didn’t have to type out all that boring python stuff every time I wanted to use it.
Step #1: Create setup.py
First off, I needed to create a basic setup.py script in my script’s directory. Mine looks a little something like this:
#setup.py
from setuptools import setup
setup(
name='mysupercoolscript',
version='0.0.1',
entry_points={
'console_scripts': [
'mysupercoolscript=mysupercoolscript:mysupercoolscript'
]
}
)
Easy enough. Just need to choose a name and replace mysupercoolscript with your own name..
Step #2: Create your CLI script
Next up: Creating the actual mysupercoolscript.py script to run my commands, options and other awesome click things. I created a group (that is used as my CLI tool name) that has one command: ‘useful_command’. This will go in the same directory as my setup.py script.
#mysupercoolscript.py
import os
import click
import sys
@click.group()
@click.pass_context
def mysupercoolscript(self):
pass
@mysupercoolscript.command()
def useful_command():
"""Does something useful"""
print("Looks like you got it working, finally.")
cli = click.CommandCollection(sources=[mysupercoolscript])
if __name__ == '__main__':
mysupercoolscript()
Step #3: Run pip install -e
Now that we have everything setup, we need to do the important part. This is where I ran the instruction:
pip install -e
The -e option is cool as it allows you to continue editing your very own super cool script even after installing it.
As my script is in ‘C:\Dojofive\blogs\cli-tool’, my command was:
pip install -e C:\\Dojofive\\blogs\\cli-tool

Et Voila
$ mysupercoolscript useful_command
And there it is! Just a sleek and elegant as I ever dreamed it would be. This may not look to be a huge change but small features can really bring a product together!

What are some things you’re struggling with on your CLI? Feel free to email me directly at [email protected] if you would like help.
Dojo Five can help you with your embedded projects – from a CLI to automating your firmware builds.
Check out our services | Check out our Emedded CI Platform
Or contact us at [email protected]