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