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.

74 lines
2.5 KiB

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