Welcome to console-menu’s documentation!

Contents:

Installation

Everyone should run:

pip install console-menu

Usage

First things first, import the package:

import consolemenu

Or just import what you need:

from consolemenu import ConsoleMenu

from consolemenu.items import FunctionItem, SubmenuItem, CommandItem

Then create a menu:

menu = ConsoleMenu("This is a menu!", "It has a subtitle too!")

Create menu items for each choice you need:

command_item = CommandItem("Run a console command", "touch hello.txt")

function_item = FunctionItem("Call a function", input, ["Enter some input"])

To add other menus as submenus, use a SubmenuItem, setting the menu property in the constructor so the submenu’s parent is set properly:

submenu = ConsoleMenu("This is the submenu")

submenu_item = SubmenuItem("Show a submenu", submenu, menu=menu)

Add the items to the menu:

menu.append_item(command_item)

menu.append_item(function_item)

menu.append_item(submenu_item)

Then start the menu:

menu.start()

After that, the menu will spawn its own thread and go about its business. If you want to wait on the user to finish with the menu before continuing, call:

menu.join()

To combine these two and simply show a menu and immediately wait for the user to exit the menu, call:

menu.show()

Getting a selection

If you have a list of strings, and you want to allow the user to select one, you can use a SelectionMenu:

from consolemenu import SelectionMenu

a_list = ["red", "blue", "green"]

selection = SelectionMenu.get_selection(a_list)

Which is equivalent to:

from consolemenu import SelectionMenu

a_list=["red", "blue", "green"]

menu = SelectionMenu(a_list,"Select an option")

menu.show()

menu.join()

selection = menu.selected_option

API Reference

ConsoleMenu — Standard menu class

class consolemenu.ConsoleMenu(title=None, subtitle=None, screen=None, formatter=None, prologue_text=None, epilogue_text=None, clear_screen=True, show_exit_option=True, exit_option_text='Exit', exit_menu_char=None)[source]

A class that displays a menu and allows the user to select an option.

Parameters:
  • title (str) – The title of the menu, or a method reference that returns a string.
  • subtitle (str) – The subtitle of the menu, or a method reference that returns a string.
  • screen (consolemenu.screen.Screen) – The screen object associated with this menu.
  • formatter (MenuFormatBuilder) – The MenuFormatBuilder instance used to format this menu.
  • prologue_text (str) – Text or method reference to include in the “prologue” section of the menu.
  • epilogue_text (str) – Text or method reference to include in the “epilogue” section of the menu.
  • show_exit_option (bool) – Specifies whether this menu should show an exit item by default. Defaults to True. Can be overridden when the menu is started.
  • exit_option_text (str) – Text for the Exit menu item. Defaults to ‘Exit’.
  • exit_menu_char (str) – Character to use for exiting the menu. Defaults to None.
  • clear_screen (bool) – Set to False to disable clearing of screen between menus
cls.currently_active_menu

Class variable that holds the currently active menu or None if no menu is currently active (e.g. when switching between menus)

Type:ConsoleMenu
items

The list of MenuItems that the menu will display

Type:list of MenuItem
parent

The parent of this menu

Type:ConsoleMenu
previous_active_menu

the previously active menu to be restored into the class’s currently active menu

Type:ConsoleMenu
current_option

The currently highlighted menu option

Type:int
selected_option

The option that the user has most recently selected

Type:int
current_item

The item corresponding to the menu option that is currently highlighted, or None.

Type:consolemenu.items.MenuItem
selected_item

The item in items that the user most recently selected, or None.

Type:consolemenu.items.MenuItem
start(show_exit_option=None)[source]

Start the menu in a new thread and allow the user to interact with it. The thread is a daemon, so join() should be called if there’s a possibility that the main thread will exit before the menu is done

Parameters:show_exit_option (bool) – Specify whether the exit item should be shown, defaults to the value set in the constructor
join(timeout=None)[source]

Should be called at some point after start() to block until the menu exits.

Parameters:timeout (Number) – How long to wait before timing out.
show(show_exit_option=None)[source]

Calls start and then immediately joins.

Parameters:show_exit_option (bool) – Specify whether the exit item should be shown, defaults to the value set in the constructor

Item Management

append_item(item)[source]

Add an item to the end of the menu before the exit item.

Parameters:item (MenuItem) – The item to be added.
add_exit()[source]

Add the exit item if necessary. Used to make sure there aren’t multiple exit items.

Returns:True if item needed to be added, False otherwise.
Return type:bool
remove_exit()[source]

Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else.

Returns:True if item needed to be removed, False otherwise.
Return type:bool

User interaction

get_input()[source]

Can be overridden to change the input method. Called in process_user_input()

Returns:the ordinal value of a single character
Return type:int
process_user_input()[source]

Gets the next single character and decides what to do with it

draw()[source]

Refresh the screen and redraw the menu. Should be called whenever something changes that needs to be redrawn.

go_to(option)[source]

Go to the option entered by the user as a number

Parameters:option (int) – the option to go to
go_up()[source]

Go up one, wrap to end if necessary

go_down()[source]

Go down one, wrap to beginning if necessary

select()[source]

Select the current item and run it

exit()[source]

Signal the menu to exit, then block until it’s done cleaning up

State management

is_alive()[source]

Check whether the thread is stil alive.

Returns:True if the thread is still alive; False otherwise.
Return type:bool
wait_for_start(timeout=None)[source]

Block until the menu is started.

Parameters:timeout – How long to wait before timing out.
Returns:False if timeout is given and operation times out, True otherwise. None before Python 2.7.
Return type:bool
pause()[source]

Temporarily pause the menu until resume is called.

resume()[source]

Sets the currently active menu to this one and resumes it.

is_running()[source]

Check if the menu has been started and is not paused.

Returns:True if the menu is started and hasn’t been paused; False otherwise.
Return type:bool

SelectionMenu — Quickly get a selection

Bases: consolemenu.ConsoleMenu

class consolemenu.SelectionMenu(strings, title=None, subtitle=None, screen=None, formatter=None, prologue_text=None, epilogue_text=None, show_exit_option=True, exit_option_text='Exit', clear_screen=True)[source]

A menu that simplifies item creation, just give it a list of strings and it builds the menu for you

Parameters:
  • strings (list of str) – The list of strings this menu should be built from.
  • title (str) – The title of the menu.
  • subtitle (str) – The subtitle of the menu.
  • screen (consolemenu.screen.Screen) – The screen object associated with this menu.
  • formatter (MenuFormatBuilder) – The MenuFormatBuilder instance used to format this menu.
  • prologue_text (str) – Text to include in the “prologue” section of the menu.
  • epilogue_text (str) – Text to include in the “epilogue” section of the menu.
  • show_exit_option (bool) – Specifies whether this menu should show an exit item by default. Defaults to True. Can be overridden when the menu is started.
  • exit_option_text (str) – Text for the Exit menu item. Defaults to ‘Exit’.
  • clear_screen (bool) – Set to False to disable clearing of screen between menus
classmethod get_selection(strings, title='Select an option', subtitle=None, show_exit_option=True, _menu=None)[source]

Single-method way of getting a selection out of a list of strings.

Parameters:
  • strings (list of str) – The list of strings this menu should be built from.
  • title (str) – The title of the menu.
  • subtitle (str) – The subtitle of the menu.
  • show_exit_option (bool) – Specifies whether this menu should show an exit item by default. Defaults to True.
  • _menu – Should probably only be used for testing, pass in a list and the created menu used internally by the method will be appended to it
Returns:

The index of the selected option.

Return type:

int

MultiSelectMenu — Make multiple selections at one prompt

Bases: consolemenu.ConsoleMenu

class consolemenu.MultiSelectMenu(title=None, subtitle=None, formatter=None, prologue_text=None, epilogue_text=None, ack_item_completion=True, show_exit_option=True, exit_option_text='Exit', clear_screen=True)[source]

Console menu that allows the selection of multiple menu items at a single prompt.

Parameters:
  • title – The menu title.
  • subtitle – The menu subtitle.
  • formatter – The menu formatter instance for styling the menu.
  • prologue_text – The text to display in the prologue section of the menu.
  • epilogue_text – The text to display in the epilogue section of the menu.
  • show_exit_option (bool) – Determines if the exit item should be displayed.
  • exit_option_text (str) – Text for the Exit menu item. Defaults to ‘Exit’.
  • clear_screen (bool) – Set to False to disable clearing of screen between menus
append_item(item)[source]

Add an item to the end of the menu before the exit item.

Note that Multi-Select Menus will not allow a SubmenuItem to be added, as multi-select menus are expected to be used only for executing multiple actions.

Parameters:item (MenuItem) – The item to be added
Raises:TypeError – If the specified MenuIem is a SubmenuItem.
process_user_input()[source]

This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs.

Examples

All of the following inputs would have the same result:
  • 1,2,3,4
  • 1-4
  • 1-2,3-4
  • 1 - 4
  • 1, 2, 3, 4
Raises:ValueError – If the input cannot be correctly parsed.

Items

CommandItem

Bases: consolemenu.items.ExternalItem

class consolemenu.items.CommandItem(text, command, arguments=None, menu=None, should_exit=False, menu_char=None)[source]

A menu item to execute a console command

Variables:
  • text (str) – The text shown for this menu item
  • command (str) – The console command to be executed
  • arguments (list[str]) – An optional list of string arguments to be passed to the command
  • menu (ConsoleMenu) – The menu to which this item belongs
  • should_exit (bool) – Whether the menu should exit once this item’s action is done
  • menu_char (str) – The character used to select this menu item. Optional - defaults to None.
action()[source]

This class overrides this method

get_return()[source]
Returns:the exit status of the command
Return type:int

ExitItem

Bases: consolemenu.items.MenuItem

class consolemenu.items.ExitItem(text='Exit', menu=None, menu_char=None)[source]

Used to exit the current menu. Handled by consolemenu.ConsoleMenu

show(index, available_width=None)[source]

ExitItem overrides this method to display appropriate Exit or Return text.

ExternalItem

Bases: consolemenu.items.MenuItem

class consolemenu.items.ExternalItem(text, menu=None, should_exit=False, menu_char=None)[source]

A base class for items that need to do stuff on the console outside of the console menu. Sets the terminal back to standard mode until the action is done. Should probably be subclassed.

clean_up()[source]

This class overrides this method

set_up()[source]

This class overrides this method

FunctionItem

Bases: consolemenu.items.ExternalItem

class consolemenu.items.FunctionItem(text, function, args=None, kwargs=None, menu=None, should_exit=False, menu_char=None)[source]

A menu item to call a Python function

Variables:
  • text (str) – The text shown for this menu item
  • function – The function to be called
  • args (list) – An optional list of arguments to be passed to the function
  • kwargs (dict) – An optional dictionary of keyword arguments to be passed to the function
  • menu (ConsoleMenu) – The menu to which this item belongs
  • should_exit (bool) – Whether the menu should exit once this item’s action is done
  • menu_char (str) – The character used to select this menu item. Optional - defaults to None.
action()[source]

This class overrides this method

clean_up()[source]

This class overrides this method

get_return()[source]
Returns:The return value from the function call

SelectionItem

Bases: consolemenu.items.MenuItem

class consolemenu.items.SelectionItem(text, index, menu=None, menu_char=None)[source]

The item type used in consolemenu.SelectionMenu

Variables:
  • text (str) – The text shown for this menu item
  • index (int) – The index of this item in the list used to initialize the consolemenu.SelectionMenu
  • menu (ConsoleMenu) – The menu to which this item belongs
  • menu_char (str) – The character used to select this menu item. Optional - defaults to None.
get_return()[source]
Returns:The index of this item in the list of strings
Return type:int

Functions

consolemenu.clear_terminal()[source]

Call the platform specific function to clear the terminal: cls on windows, reset otherwise

Screen

class consolemenu.screen.Screen[source]

Class representing a console screen.

static clear()[source]

Clear the screen.

static flush()[source]

Flush any buffered standard output to screen.

input(prompt='')[source]

Prompt the end user for input.

Parameters:prompt (str, optional) – The message to display as the prompt.
Returns:The input provided by the user.
static printf(*args)[source]

Print the specified arguments to the screen.

Parameters:*args – Variable length argument list.
static println(*args)[source]

Print the specified arguments to the screen, including an appended newline character.

Parameters:*args – Variable length argument list.
screen_height

The screen height in rows.

Type:int
screen_width

The screen width in columns.

Type:int

Formatting

Prompts

PromptFormatter

class consolemenu.prompt_utils.PromptFormatter[source]

Class for formatting a text input prompt, to allow overriding the message as desired.

Default answers will appear in [square brackets] and allow the user to return that answer by simply pressing the Enter button.

If a ‘Quit’ option is desired, set enable_quit to True and provide a quit_string (default is ‘q’) and a quit_message (default is ‘(enter q to Quit)’).

static format_prompt(prompt=None, default=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)')[source]

Format the message presented to the user during input prompting.

Parameters:
  • prompt (str) – The message to ask the user.
  • default (str, optional) – The default answer if user does not provide explicit input.
  • enable_quit (bool, optional) – Flag to determine whether a Quit option will be presented.
  • quit_string (str, optional) – The string the user must input to quit (default is ‘q’).
  • quit_message (str, optional) – The message to the user explaining how to Quit.
Returns:

The formatted prompt string.

Return type:

str

PromptUtils

class consolemenu.prompt_utils.PromptUtils(screen, prompt_formatter=None)[source]

Utility class with various routines for prompting for user input.

Creates a new instance of ConsoleUtils with the specified console. If no console was specified, creates a new default console using the ConsoleFactory.

Parameters:
clear()[source]

Clear the screen.

confirm_answer(answer, message=None)[source]

Prompts the user to confirm a question with a yes/no prompt. If no message is specified, the default message is: “You entered {}. Is this correct?”

Parameters:
  • answer (str) – The answer to confirm.
  • message (str, optional) – Optional message if a different confirmation prompt is desired.
Returns:

True if the user confirmed Yes, or False if user specified No.

Return type:

bool

enter_to_continue(message=None)[source]

A console prompt to ask the user to ‘Press [Enter] to continue’.

Parameters:message (str, optional) – A message to display in place of the default.
input(prompt=None, default=None, validators=None, enable_quit=False, quit_string='q', quit_message='(enter q to Quit)')[source]

Generic prompt the user for input.

Parameters:
  • prompt (str) – The message to prompt the user.
  • default (str, optional) – The default value to suggest as an answer.
  • validators (BaseValidator, optional) – The list of validators to perform input validation.
  • enable_quit (bool, optional) – Specifies whether the user can cancel out of the input prompt.
  • quit_string (str, optional) – The string which the user must input in order to quit.
  • quit_message (str, optional) – The message to explain how to quit.
Returns:

an InputResult tuple.

Return type:

InputResult

input_password(message=None)[source]

Prompt the user for a password or other confidential data.

This is equivalent to the input() method, but does not echo inputted characters to the screen.

Parameters:message (str) – The prompt message.
Returns:The password provided by the user.
Return type:str
printf(*args)[source]

Prints the specified arguments to the screen.

Parameters:*args – Variable length argument list.
println(*args)[source]

Prints the specified arguments to the screen, followed by a newline character.

Parameters:*args – Variable length argument list.
prompt_and_confirm_password(message)[source]

Prompt for a password using the given message, then prompt a second time for a confirmation password, and verify both provided passwords match. If the passwords do not match, an error is displayed, “Passwords do not match”, and the user must input both passwords again.

Parameters:message (str) – The prompt message.
Returns:The password.
Return type:str
prompt_for_bilateral_choice(prompt, option1, option2)[source]

Prompt the user for a response that must be one of the two supplied choices.

NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options.

Parameters:
  • prompt (str) – The prompt to present the choices to the user.
  • option1 (str) – The first option.
  • option2 (str) – The second option.
Returns:

The choice selected by the user.

Return type:

str

prompt_for_numbered_choice(choices, title=None, prompt='>')[source]

Displays a numbered vertical list of choices from the provided list of strings.

Parameters:
  • choices (list of str) – The list of choices to display.
  • title (str, optional) – Optional title to display above the numbered list.
  • prompt (str) – The prompt string. Default is “>”.
Returns:

The index of selected choice.

Return type:

int

prompt_for_trilateral_choice(prompt, option1, option2, option3)[source]

Prompt the user for a response that must be one of the three supplied choices.

NOTE: The user input verification is case-insensitive, but will return the original case provided by the given options.

Parameters:
  • prompt (str) – The prompt to present the choices to the user.
  • option1 (str) – The first option.
  • option2 (str) – The second option.
  • option3 (str) – The third option.
Returns:

The choice selected by the user.

Return type:

str

prompt_for_yes_or_no(prompt)[source]

Prompts the user with the specified question, and expects a yes (y) or no (n) response, returning a boolean value representing the user’s answer.

Parameters:prompt (str) – The prompt to display to the user.
Returns:True for yes, False for no.
Return type:bool
screen

The Screen instance.

Type:consolemenu.screen.Screen
validate_input(input_string, validators)[source]

Validate the given input string against the specified list of validators.

Parameters:
  • input_string (str) – The input string to verify.
  • validators (list of BaseValidator) – The list of validators.
Returns:

The validation result. True if the input is valid; False otherwise.

Return type:

bool

Raises:

InvalidValidator – If the list of validators contains an invalid BaseValidator class.

UserQuit

class consolemenu.prompt_utils.UserQuit[source]

Exception raised when a user chooses to Quit from an input prompt.

Indices and tables