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