-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinteractive.py
80 lines (63 loc) · 1.89 KB
/
interactive.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
def output(*args):
print(*args)
def promptInput(prompt, fmt='', default=''):
if fmt != '':
promptf = '{} [{}]'.format(prompt, fmt)
elif default != '':
promptf = '{} [{}]'.format(prompt, default)
else:
promptf = prompt
promptf = '{}: '.format(promptf)
while True:
inp = input(promptf)
if inp != '':
return inp
elif default != '' and inp == '':
return default
# empty input with no default
output('Please enter non-empty string.')
def promptValidate(prompt, validator, fmt='', default=''):
while True:
inp = promptInput(prompt, fmt=fmt, default=default)
v = validator(inp)
if v == '':
return inp
output('Invalid input (case-insensitive): {}'.format(v))
def selectorValidator(options, default=''):
def validator(inp):
i = inp.lower()
if default != '':
if i == default.lower() or i == '':
return ''
if i in options:
return ''
return i
return validator
'''
e.g. promptInput('Do you want to continue?', ['n'], default='y')
input with validation
'''
def promptSelect(prompt, alts, default=''):
default = default.lower()
options = []
if default != '':
options.append(default.upper())
for a in alts:
options.append(a.lower())
fmt = '/'.join(options)
validator = selectorValidator(options, default=default)
inp = promptValidate(prompt, validator, fmt=fmt, default=default)
return inp.lower()
def newFileValidator():
def validator(inp):
try:
if os.path.exists(inp):
return '{} already exists'.format(inp)
else:
open(inp, 'w').close()
os.unlink(inp)
return ''
except OSError as e:
return str(e)
return validator