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