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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
|
# Copyright (C) 2011 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Console output routines.
$Repo: git://git.sugarlabs.org/alsroot/codelets.git$
$File: src/printf.py$
$Date: 2012-10-22$
"""
import sys
import logging
#: Disable/enable non-status output.
VERBOSE = True
#: Disable/enable any output.
QUIET = False
RESET = '\033[0m'
BOLD = '\033[1m'
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = \
['\033[1;%dm' % (30 + i_) for i_ in range(8)]
stdout = sys.stdout
stderr = sys.stderr
_hints = []
_last_line_len = 0
_last_progress = []
_screen_width = None
def dump(message, *args):
"""Print verbatim text.
:param message:
text to print
:param \*args:
`%` arguments to expand `message` value
"""
_dump(False, stdout, '', [message, args], '\n')
def info(message, *args):
"""Print information text.
:param message:
text to print
:param \*args:
`%` arguments to expand `message` value
"""
_dump(True, stderr, None, [message, args], '\n')
_dump_progress()
def exception(message=None, *args):
"""Print exception text.
Call this function in `try..except` block after getting exceptions.
:param message:
text to print
:param \*args:
`%` arguments to expand `message` value
"""
import traceback
klass, error, tb = sys.exc_info()
tb_list = []
for line in traceback.format_exception(klass, error, tb):
tb_list.extend([i.rstrip() for i in line.strip().split('\n')])
if type(error).__name__ == 'dbus.exceptions.DBusException':
dbus_tb = str(error).split('\n')
if len(dbus_tb) == 1:
error = dbus_tb[0]
else:
# Strip the last empty line
del dbus_tb[-1]
error = '%s:%s' % \
(dbus_tb[0].split(':')[0], dbus_tb[-1].split(':', 1)[-1])
if message and args:
message = message % args
error = str(error) or 'Something weird happened'
if message:
message += ': %s' % error
else:
message = str(error)
_dump(True, stderr, None, message, '\n')
if logging.getLogger().level > logging.INFO:
hint('Use -D argument for debug info, '
'-DD for full debuging output and tracebacks')
elif logging.getLogger().level > logging.DEBUG:
hint('Use -DD argument for full debuging output and tracebacks')
else:
for i in tb_list:
_dump(True, stderr, ' ', i, '\n')
_dump_progress()
def scan_yn(message, *args):
"""Request for Y/N input.
:param message:
prefix text to print
:param \*args:
`%` arguments to expand `message` value
:returns:
`True` if user's input was `Y`
"""
_dump(True, stderr, None, [message, args], ' [Y/N] ')
answer = raw_input()
_dump_progress()
return answer and answer in 'Yy'
def progress(message, *args):
"""Print status line text.
Status line will be shown as the last line all time and will be cleared
on program exit.
:param message:
prefix text to print
:param \*args:
`%` arguments to expand `message` value
"""
_last_progress[:] = [message, args]
_dump_progress()
def clear_progress():
"""Clear status line on program exit."""
if _last_line_len:
stderr.write(chr(13) + ' ' * _last_line_len + chr(13))
def hint(message, *args):
"""Add new hint.
All hint will be queued to print them at once in `flush_hints()` function
on program exit.
:param message:
prefix text to print
:param \*args:
`%` arguments to expand `message` value
"""
if args:
message = message % args
_hints.append(message)
def flush_hints():
"""Print all queued hints."""
clear_progress()
if _hints:
dump('')
while _hints:
_dump(True, stderr, '-- Hint: ', _hints.pop(0), '\n')
def _dump(is_status, stream, prefix, *args):
if not VERBOSE or QUIET:
return
global _last_line_len
global _screen_width
if _screen_width is None:
try:
import curses
curses.setupterm()
_screen_width = curses.tigetnum('cols') or 80
except Exception, error:
logging.info('Cannot get screen width: %s', error)
_screen_width = 80
if prefix is None:
prefix = '-- '
clear_progress()
_last_line_len = 0
for i in [prefix] + list(args):
if isinstance(i, list):
if i:
message, message_args = i
if message_args:
message = message % message_args
else:
message = i
stream.write(message)
if is_status:
_last_line_len += len(message)
_last_line_len = min(_last_line_len, _screen_width)
def _dump_progress():
_dump(True, stderr, ' ', _last_progress, chr(13))
stderr.flush()
|