You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.4 KiB

  1. from terminaltables.terminal_io import terminal_size
  2. from terminaltables import AsciiTable
  3. from textwrap import fill
  4. from pydoc import pipepager, tempfilepager, plainpager, plain
  5. import datetime
  6. import os
  7. import sys
  8. def getpager():
  9. """Decide what method to use for paging through text."""
  10. if not hasattr(sys.stdin, "isatty"):
  11. return plainpager
  12. if not hasattr(sys.stdout, "isatty"):
  13. return plainpager
  14. if not sys.stdin.isatty() or not sys.stdout.isatty():
  15. return plainpager
  16. use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
  17. if use_pager:
  18. if sys.platform == 'win32': # pipes completely broken in Windows
  19. return lambda text: tempfilepager(plain(text), use_pager)
  20. elif os.environ.get('TERM') in ('dumb', 'emacs'):
  21. return lambda text: pipepager(plain(text), use_pager)
  22. else:
  23. return lambda text: pipepager(text, use_pager)
  24. if os.environ.get('TERM') in ('dumb', 'emacs'):
  25. return plainpager
  26. if sys.platform == 'win32':
  27. return lambda text: tempfilepager(plain(text), 'more <')
  28. if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  29. return lambda text: pipepager(text, 'less -X')
  30. def str_coerce(s, **kwargs):
  31. if isinstance(s, datetime.datetime):
  32. return s.strftime(kwargs['datetime_format'])
  33. else:
  34. return str(s)
  35. def create_table(list_param, datetime_format):
  36. rows = []
  37. for row in list_param:
  38. rows.append([])
  39. for item in row:
  40. rows[-1].append(str_coerce(item, datetime_format=datetime_format))
  41. return AsciiTable(rows)
  42. def render_table(table: AsciiTable, interactive=True):
  43. '''Do all wrapping to make the table fit in screen'''
  44. table.inner_row_border = True
  45. data = table.table_data
  46. terminal_width = terminal_size()[0]
  47. n_cols = len(data[0])
  48. even_distribution = terminal_width // n_cols
  49. for row_num, row in enumerate(data):
  50. for col_num, col_data in enumerate(row):
  51. if len(col_data) > even_distribution:
  52. if col_num != n_cols - 1:
  53. data[row_num][col_num] = fill(col_data, even_distribution)
  54. else:
  55. data[row_num][col_num] = ''
  56. data[row_num][col_num] = fill(
  57. col_data, table.column_max_width(col_num))
  58. if interactive:
  59. pager = getpager()
  60. pager(table.table)
  61. else:
  62. print(table.table)