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

This is Day 10 of the #100DaysOfPython challenge.

This post will use the PyInquirer library to demonstrate how to add some command line prompts to make it easier to build an interactive program.

It will build off the work done on learning Python Fire basics in a previous blog post.

Prerequisites

  1. Familiarity with Pipenv. See here for my post on Pipenv.
  2. Building CLIs with Python.

Getting started

This code works off what was done in Building CLIs with Python.

You should already have the code. In that blog post, all code was posted into a hello-fire directory with cli.py as the main file with a few dependencies already installed.

The code is available on my GitHub repo.

We are going to add the PyInquirer to our dependencies to use in the cli.py file:

At this stage, we had a cli.py file that looks like the following:

Opening the virtual environment and running python cli.py [command] would run the program (ie python cli.py digestion run would output Burp!).

Simple input prompt

For our first prompt, we are going to update the DigestionStage class run method to default to 0 burps and request that we provide a volume.

We do this with Python Fire as a call without an value for the argument would raise an error.

We can import the prompt function and use that to get the input:

Now if we run our command line call python cli.py digestion run:

A simple input prompt is all we need to get started.

Note: We could have simply removed volume altogether but we have left is so that Python Fire can cast the input into an int via a flag --volume without a prompt.

Working with dialogs

Prompt toolkit also comes with a way to create dialogs. There are choices between simple yes/no dialogs to helps for lists of options that operate as a “radio” or “checkbox”.

Update the DigestionStage to look like the following:

We have no added digestion breakfast command that we can run with python run digestion breakfast:

Now we have a digestion breakfast command that will run the breakfast method and output the result of our input into the dialog.

Summary

We have used PyInquirer to demo a simple command line input as well as a way to pick an option from a list.

There are many examples that they have on their GitHub if you would like to learn more.

Resources and further reading

  1. The ABCs of Pipenv
  2. Building CLIs with Python Fire
  3. Pipenv
  4. PyInquirer
  5. More examples of PyInquirer
  6. Python Fire

Photo credit: pawel_czerwinski

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.