Writing a “simple” application is rarely a simple task. Even simple code for a simple task requires interactions with the quirks of your programming language, exception handling, input sanitizing, intuitive design, and much more. This is why I appreciate a library that makes development simple. One of my favorite Python libraries is Click, a module that handles every aspect of command-line options. In this article, I demonstrate how to use it.

For this tutorial, I reuse the source code of my open source rpm_query application. The rpm_query application is a collection of simple commands that can query your system’s RPM database from a terminal.

Requirements

To follow along with this tutorial, you must have:

  1. Linux distribution, preferably one that uses RPM (Like Fedora or Red Hat Enterprise Linux)
  2. Python 3.7 or greater
  3. Git
  4. A familiarity with virtual environments
  5. An Internet connection so you can download dependencies

A common CLI

This script uses a module inside the reporter package to query the RPM database:

Install it in editable mode:

See it in action:

Process command-line arguments with Click

The Click framework makes it easy to parse command-line arguments. To prove that, convert my rpm_query command to Click:

There are two big changes:

  1. Most of the boilerplate code from ArgParse is done, replaced by annotations.
  2. The Click library adds decorators to a new function called command that takes arguments and executes the RPM query.

Run the new script to confirm that it works exactly as before.

Using setuptools and Click

The Click documentation mentions that you should use setuptools to automatically create a wrapper for your tool. The documentation uses deprecated syntax for setup.py, but you can use the new setup.cfg format instead, creating a package called scripts inside the package called reporter.

A script called rpmq is created by setuptools, and it behaves exactly as the previous script, but no boilerplate code to pass arguments to Click is needed.

Next steps

  1. Download the source code for this tutorial and start experimenting.
  2. Click has great documentation and online support. Take advantage of it!
  3. Click has much more complex examples, so take a look at its gallery.

Author


Jose Vicente Nunez

System Administrator/ DevOps.

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *