Dennis O'Keeffe
3 min readAug 25, 2021
Heading image

This is Day 6 of the #100DaysOfPython challenge.

This post will use the Python Fire library to work through a simple example of setting up the library.

Prerequisites

  1. Familiarity with Pipenv. See here for my post on Pipenv.

Getting started

Let’s create the hello-fire directory and install python-fire.

We will also create a file cli.py to hold our CLI script.

We are now ready to add a script.

The CLI script

For our demo example, we are going to take a slightly modified version of grouping commands script to demo how to run subcommands.

Our aim is to have the following commands:

| Command | Description | | — — — — — — — — — | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — | | ingestion run | Print a message to the console to highlight that we have run the ingestion script | | digestion status | Print a message based on the value of the Digestion class satiated property | | digestion run | Print a message to the console to highlight that we have run the digestion script and set the value of satiated to True | | run | Run both ingestion and digestion run commands and the digestion status |

Adding the code

We set the base commands through the Pipeline class and the subcommands through their own class that is initiated as properties of the Pipeline class.

If you notice the optional volume argument for DigestionStage.run, it is used to set the volume of the Digestion class based on an argument passed to the CLI (defaulting to 1).

Running the script

To run the script, we need to ensure we are running the Pipenv virtual environment.

We can do this with pipenv shell.

Once, in the shell, we can run our script and see the results:

Running through our script, we can now see the results of our work.

Notice that the status property of the Digestion class is set to True when we run the run command and the number of "Burp!" messages printed is based on the volume argument passed to the run command.

Summary

Today’s post demonstrated how to use the python-fire package to write easier CLI scripts with their own subcommands and instance-managed state.

Of most languages that I have used, it must be said that python-fire has been one of the most approachable libraries I have seen for building out CLI tools.

Resources and further reading

  1. The ABCs of Pipenv for the minimum you will need.
  2. Hello, JupyterLab.
  3. Python Fire
  4. Pipenv

Photo credit: cullansmith

Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.

I write content for AWS, Kubernetes, Python, JavaScript and more. To view all the latest content, be sure to visit my blog and subscribe to my newsletter. Follow me on Twitter.

Dennis O'Keeffe
Dennis O'Keeffe

No responses yet