How to Create Main Menus for CLI Scripts in Python

The aim of this page📝 is to share an approach for the simple creation of terminal menus with Python scripts, ideally utilizing a simple library function for all menus.

  1. Given a list ["retry", "abort", cancel"]
  2. Print the list with numbers next to the list starting from 1

3. Return 1-indexed value in the list

I am building an automation platform hosting scripts in a dedicated folder

  • If curious, see the insightful treatment of Platform < The Evolution of Automation at Google < Site Reliability Engineering
  • I have scripts in a folder which I execute to get the menu listing all utils with a keystroke (handled by a bash alias)
  • …that is a different story altogether, let’s just look at the source code, the most important are the 4 last lines
  • ……and of course, print("running => ", selected_tool) is just for demo purposes here, I'll look_up a proper utility
  • Let’s run that

The menu is a class with members separated into a command method (print) and a query method (get)

  1. the object is initialized with a random list — a source for your future menu
  2. the command print_menu uses enumerate() method to create a numbered/ordered list from menu_items (for enumerate, see https://medium.com/p/616cbf2de913)
  3. the query method select_menu_items() asks a user for the number and returns the 1-indexed item from a list by decrementing the client input

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com