Source code for MPF.commonHelpers.interaction

#
# functions useful for user interaction
#

[docs]class outputHelper(object): def __init__(self, rows): self.rows = rows
[docs] def printTable(self): printTable(self.rows)
[docs]def promptYN(text, trials=3): # This function has problems when reading from stdin print (text + '[yn]') if trials == 0: return False choice = raw_input() if choice == 'y': return True elif choice == 'n': return False else: return promptYN('could not recognize answer, try again:' + text, trials-1)
[docs]def promptInput(message): print(message) text = raw_input() if text == '': if promptYN('add empty field?'): return text else: promptInput(message) else: return text
[docs]def humanReadableSize(size, suffix='B'): # From http://stackoverflow.com/a/1094933 for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(size) < 1024.0: return "%3.1f%s%s" % (size, unit, suffix) size /= 1024.0 return "%.1f%s%s" % (size, 'Yi', suffix)
[docs]def printTable(table): """ takes list of rows and turns it to printable string """ nColumns = len(table[0]) maxWidth = [0] * nColumns # convert table to strings for i, row in enumerate(table): for j, field in enumerate(row): table[i][j] = str(table[i][j]) for row in table: if len(row) != nColumns: logger.error("{} does not have {} columns".format(row, nColumns)) raise IndexError for i, field in enumerate(row): if len(field) > maxWidth[i]: maxWidth[i] = len(field) spacer = '{:{fill}^{width}}\n'.format('', fill="#", width=sum(maxWidth)+nColumns) text = spacer for row in table: for i, field in enumerate(row): text += ' {:<{width}}'.format(field, width=maxWidth[i]+1) text += '\n' text += spacer return text