-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyselect.py
61 lines (51 loc) · 1.57 KB
/
pyselect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -*- coding: utf-8 -*-
__title__ = "pyselect"
__version__ = "0.2.0"
__author__ = "Matthew Behrens"
__license__ = "MIT"
__copyright__ = "Copyright 2013 Matthew Behrens"
# updated to work with Python 3
import sys
def select(options=None, lam="option"):
"""pass in a list of options, prompt the user to select one, and return the selected option or None"""
if not options:
return None
width = len(str(len(options)))
for x, option in enumerate(options):
sys.stdout.write("{:{width}}) {}\n".format(x + 1, eval(lam), width=width))
sys.stdout.write("{:>{width}} ".format("#?", width=width + 1))
sys.stdout.flush()
if sys.stdin.isatty():
# regular prompt
try:
response = input().strip()
except (EOFError, KeyboardInterrupt):
# handle ctrl-d, ctrl-c
response = ""
else:
# try connecting to current tty, when using pipes
sys.stdin = open("/dev/tty")
try:
response = ""
while True:
response += sys.stdin.read(1)
if response.endswith("\n"):
break
except (EOFError, KeyboardInterrupt):
sys.stdout.flush()
pass
try:
response = int(response) - 1
except ValueError:
return None
if response < 0 or response >= len(options):
return None
return options[response]
def main(args=None):
if args is None:
args = sys.argv[1:]
response = select(args)
if response:
print(response)
if __name__ == "__main__":
main()