Python in the Command Line: A Tutorial on Click

Introduction

While I was spending my weekend on one of my favorite pastimes, writing Python code, and found a way to generate a 3D QR code of my WIFI password. In the process, I had some interesting epiphanies, mainly that Command Line Interfaces (CLIs) and Web Apps share some striking commonalities:

CLIs and web apps are nothing more than text end points to arbitrary code!

To show this in detail, I’ll use the code base from my 3D model QR code project and create a command-line interface from the functions I used.

Building a Command-Line Interface (CLI)

A CLI lets you access a program from the command line, say, the Linux/macOS bash shell or a Windows command prompt. A CLI lets you run scripts. For example a CLI would allow us to programmatically generate as many QR codes as we wish, with a single command.

One disadvantage of a command-line interface to keep in mind is that it requires the end user to be familiar with supported text commands. This can feel somewhat like memorizing incantations to perform magic (well, this does seem to jive with Clarke’s law). A small price to pay for technological excellence!

Overview: Preparation to build a CLI

In the name of “good software engineering”, we are going to first organize our functions a bit, and prepare to build this into a Python package that can be easily distributed. The final directory structure we are targeting is as follows:

├── environment.yml
├── qrwifi
│   ├── __init__.py
│   ├── app.py
│   ├── cli.py
│   ├── functions.py **
│   └── templates
│       ├── index.html.j2
│       ├── qr.html.j2
│       └── template.html.j2
└── setup.py

(From this point on, I will highlight the file that we will be editing with a double asterisk (**)).

Functions Library

Let’s start by creating functions.py. It should house the functions that we can import and call on.

Back to Top