Skip to content

Instantly share code, notes, and snippets.

@TimelessP
Last active November 13, 2021 13:09
Show Gist options
  • Save TimelessP/85b1639dfab3561425dbf8c67cdcfd59 to your computer and use it in GitHub Desktop.
Save TimelessP/85b1639dfab3561425dbf8c67cdcfd59 to your computer and use it in GitHub Desktop.
minimalmenu.py is minimal
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""minimalmenu.py by @TimelessP
https://gist.github.com/TimelessP/85b1639dfab3561425dbf8c67cdcfd59
"""
import subprocess
import inspect
import sys
def print_menu(menu_string):
"""Prints the menu. The first line is the menu title. Remaining lines are
printed as indexed options. Returns an integer of the number of items plus
one."""
index = 0
for index, line in enumerate(menu_string.split('\n')):
if index == 0:
print("\n\x1b[1;4m%s\x1b[0m" % line)
else:
print("%d. %s" % (index, line))
print('%d. Exit %s' % (index + 1, menu_string.split('\n')[0]))
return len(menu_string.split('\n')) + 1
def get_menu_choice():
"""Prints the menu and prompts the user for a choice. Returns the choice
number as an integer."""
# The pylint warnings are quite reasonable. Is there a better way of
# obtaining the caller's function as a reference?
# [W0123] 27 : get_menu_choice: Use of eval
# [W0212] 27 : get_menu_choice: Access to a protected member _getframe of
# a client class
menu_string = inspect.getdoc(eval(sys._getframe().f_back.f_code.co_name))
while True:
item_count = print_menu(menu_string)
try:
choice = int(input('? '))
if choice in range(1, item_count):
break
except (EOFError, KeyboardInterrupt, ValueError):
pass
print("\x1b[1mError: invalid choice\x1b[0m")
return choice
def menu_submenu():
"""Sub-menu
Print hello"""
while True:
choice = get_menu_choice()
if choice == 1:
print("Hello!")
elif choice == 2:
break
def menu_main():
"""Main Menu
Current date and time
Echo hello
Sub-menu…"""
while True:
choice, exitcode = get_menu_choice(), None
if choice == 1:
exitcode = subprocess.call(('bash', '-c',
'echo -n "Currently: " ; date'))
elif choice == 2:
exitcode = subprocess.call(('bash', '-c', 'echo "Hello"'))
elif choice == 3:
menu_submenu()
elif choice == 4:
break
if exitcode is not None:
print('Exit code: %d' % exitcode)
if __name__ == "__main__":
menu_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment