Revision 001200c3 kamaki/cli/utils.py
b/kamaki/cli/utils.py | ||
---|---|---|
257 | 257 |
|
258 | 258 |
|
259 | 259 |
def format_size(size): |
260 |
units = ('B', 'K', 'M', 'G', 'T')
|
|
260 |
units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
|
|
261 | 261 |
try: |
262 | 262 |
size = float(size) |
263 | 263 |
except ValueError as err: |
... | ... | |
265 | 265 |
for unit in units: |
266 | 266 |
if size < 1024: |
267 | 267 |
break |
268 |
size /= 1024 |
|
269 |
s = ('%.1f' % size)
|
|
270 |
if '.0' == s[-2:]:
|
|
271 |
s = s[:-2]
|
|
268 |
size /= 1024.0
|
|
269 |
s = ('%.2f' % size)
|
|
270 |
while '.' in s and s[-1] in ('0', '.'):
|
|
271 |
s = s[:-1]
|
|
272 | 272 |
return s + unit |
273 | 273 |
|
274 | 274 |
|
275 |
def to_bytes(size, format): |
|
276 |
""" |
|
277 |
:param size: (float) the size in the given format |
|
278 |
:param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB |
|
279 |
|
|
280 |
:returns: (int) the size in bytes |
|
281 |
""" |
|
282 |
format = format.upper() |
|
283 |
if format == 'B': |
|
284 |
return int(size) |
|
285 |
size = float(size) |
|
286 |
units_dc = ('KB', 'MB', 'GB', 'TB') |
|
287 |
units_bi = ('KIB', 'MIB', 'GIB', 'TIB') |
|
288 |
|
|
289 |
factor = 1024 if format in units_bi else 1000 if format in units_dc else 0 |
|
290 |
if not factor: |
|
291 |
raise ValueError('Invalid data size format %s' % format) |
|
292 |
for prefix in ('K', 'M', 'G', 'T'): |
|
293 |
size *= factor |
|
294 |
if format.startswith(prefix): |
|
295 |
break |
|
296 |
return int(size) |
|
297 |
|
|
298 |
|
|
275 | 299 |
def dict2file(d, f, depth=0): |
276 | 300 |
for k, v in d.items(): |
277 | 301 |
f.write('%s%s: ' % ('\t' * depth, k)) |
... | ... | |
325 | 349 |
return terms |
326 | 350 |
|
327 | 351 |
|
328 |
def ask_user(msg, true_responses=('Y', 'y')):
|
|
352 |
def ask_user(msg, true_resp=['Y', 'y']):
|
|
329 | 353 |
"""Print msg and read user response |
330 | 354 |
|
331 |
:param true_responses: (tuple of chars)
|
|
355 |
:param true_resp: (tuple of chars) |
|
332 | 356 |
|
333 | 357 |
:returns: (bool) True if reponse in true responses, False otherwise |
334 | 358 |
""" |
335 |
stdout.write('%s (%s for yes):' % (msg, true_responses))
|
|
359 |
stdout.write('%s (%s or enter for yes):' % (msg, ', '.join(true_resp)))
|
|
336 | 360 |
stdout.flush() |
337 |
user_response = stdin.read(1) |
|
338 |
return user_response[0] in true_responses |
|
361 |
user_response = stdin.readline() |
|
362 |
return user_response[0] in true_resp + ['\n'] |
Also available in: Unified diff