forked from marwano/whiptail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhiptailPy.py
78 lines (63 loc) · 2.69 KB
/
whiptailPy.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
from __future__ import print_function
import sys
import shlex
import itertools
from subprocess import Popen, PIPE
from collections import namedtuple
__version__ = '1.0'
PY3 = sys.version_info[0] == 3
string_types = str if PY3 else basestring
Response = namedtuple('Response', 'returncode value')
def flatten(data):
return list(itertools.chain.from_iterable(data))
class Whiptail(object):
def __init__(self, title='', backtitle='', height=10, width=50,
auto_exit=True):
self.title = title
self.backtitle = backtitle
self.height = height
self.width = width
self.auto_exit = auto_exit
def run(self, control, msg, extra=(), exit_on=(1, 255)):
cmd = [
'whiptail', '--title', self.title, '--backtitle', self.backtitle,
'--' + control, msg, str(self.height), str(self.width)
]
cmd += list(extra)
p = Popen(cmd)
out, err = p.communicate()
if self.auto_exit and p.returncode in exit_on:
print('User cancelled operation.')
sys.exit(p.returncode)
return Response(p.returncode, err)
def calc_height(self, msg):
height_offset = 8 if msg else 7
return [str(self.height - height_offset)]
def showlist(self, control, msg, items, prefix):
if isinstance(items[0], string_types):
items = [(i, '', 'OFF') for i in items]
else:
items = [(k, prefix + v, s) for k, v, s in items]
extra = self.calc_height(msg) + flatten(items)
return shlex.split(self.run(control, msg, extra).value)
def prompt(self, msg, default='', password=False):
control = 'passwordbox' if password else 'inputbox'
return self.run(control, msg, [default]).value
def confirm(self, msg, default='yes', yes='yes', no='no'):
defaultno = '--defaultno' if default == 'no' else ''
return self.run('yesno', msg, [defaultno, '--yes-button', yes, '--no-button', no], [255]).returncode == 0
def menu(self, msg='', items=(), prefix=' - '):
if isinstance(items[0], string_types):
items = [(i, '') for i in items]
else:
items = [(k, prefix + v) for k, v in items]
extra = self.calc_height(msg) + flatten(items)
return self.run('menu', msg, extra).value
def alert(self, msg):
self.run('msgbox', msg)
def view_file(self, path):
self.run('textbox', path, ['--scrolltext'])
def radiolist(self, msg='', items=(), prefix=' - '):
return self.showlist('radiolist', msg, items, prefix)
def checklist(self, msg='', items=(), prefix=' - '):
return self.showlist('checklist', msg, items, prefix)