]> git.phdru.name Git - m_lib.git/blob - m_lib/tty_menu.py
06e756e157c78edf2883976da04629bc3576ccdb
[m_lib.git] / m_lib / tty_menu.py
1 #! /usr/bin/env python
2 """tty menus"""
3
4
5 from __future__ import print_function
6 import string
7
8
9 try:
10    raw_input
11 except NameError:  # Python 3
12    raw_input = input
13
14
15 def hmenu(prompt, astring):
16    """
17       Writes prompt and read result
18       until result[0] is one of allowed characters (from astring),
19       and returns the character
20    """
21    while 1:
22       result = raw_input(prompt)
23       if len(result) > 0:
24          c = result[0]
25          if c in astring:
26             return c
27
28
29 def vmenu(item_list, prompt, format = "%d. %s"):
30    """
31       Prints numbered list of items and allow user to select one,
32       returns selected number. Returns -1, if user enter non-numeric string.
33    """
34    for i in range(len(item_list)):
35       print(format % (i, item_list[i]))
36    print
37
38    result = raw_input(prompt)
39
40    try:
41       result = string.atoi(result)
42    except string.atoi_error:
43       result = -1
44
45    return result
46
47
48 def test():
49    result = hmenu("Select: d)aily, w)eekly, m)onthly, c)ancel: ", "dwmc")
50    print("Answer is '%s'\n" % result)
51
52    os_list = ["DOS", "Windows", "UNIX"]
53    result = vmenu(os_list, "Select OS: ")
54    if 0 <= result < len(os_list):
55       print("Answer is '%s'\n" % os_list[result])
56    else:
57       print("Wrong selection")
58
59 if __name__ == "__main__":
60    test()