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