output.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import json
  2. import logging
  3. from collections.abc import Mapping
  4. from base64 import b64encode
  5. from .framework import Global, Task
  6. from .input_ctrl import send_msg, single_input, input_control, next_event, run_async
  7. from .output_ctl import register_callback
  8. import asyncio
  9. import inspect
  10. def set_title(title):
  11. send_msg('output_ctl', dict(title=title))
  12. def set_output_fixed_height(enabled=True):
  13. send_msg('output_ctl', dict(output_fixed_height=enabled))
  14. def text_print(text, *, ws=None):
  15. if text is None:
  16. text = ''
  17. msg = dict(command="output", spec=dict(content=text, type='text'))
  18. (ws or Global.active_ws).write_message(json.dumps(msg))
  19. def json_print(obj):
  20. text = "```\n%s\n```" % json.dumps(obj, indent=4, ensure_ascii=False)
  21. text_print(text)
  22. def put_markdown(mdcontent, lstrip=False):
  23. """
  24. 输出Markdown内容
  25. :param mdcontent: Markdown文本
  26. :param lstrip: 是否去除行开始的空白。当在函数中使用Python的三引号语法输出多行内容时,为了排版美观可能会对Markdown文本进行缩进,
  27. 这时候,可以设置lstrip来防止Markdown错误解析
  28. :return:
  29. """
  30. if lstrip:
  31. lines = (i.lstrip() for i in mdcontent.splitlines())
  32. mdcontent = '\n'.join(lines)
  33. text_print(mdcontent)
  34. def put_table(tdata, header=None):
  35. """
  36. 输出表格
  37. :param tdata: list of list|dict
  38. :param header: 列表,当tdata为字典列表时,header指定表头顺序
  39. :return:
  40. """
  41. if header:
  42. tdata = [
  43. [row.get(k, '') for k in header]
  44. for row in tdata
  45. ]
  46. def quote(data):
  47. return str(data).replace('|', r'\|')
  48. # 防止当tdata只有一行时,无法显示表格
  49. if len(tdata) == 1:
  50. tdata[0:0] = [' '] * len(tdata[0])
  51. header = "|%s|" % "|".join(map(quote, tdata[0]))
  52. res = [header]
  53. res.append("|%s|" % "|".join(['----'] * len(tdata[0])))
  54. for tr in tdata[1:]:
  55. t = "|%s|" % "|".join(map(quote, tr))
  56. res.append(t)
  57. text_print('\n'.join(res))
  58. def _format_button(buttons):
  59. """
  60. 格式化按钮参数
  61. :param buttons: button列表, button可用形式:
  62. {value:, label:, }
  63. (value, label,)
  64. value 单值,label等于value
  65. :return: [{value:, label:, }, ...]
  66. """
  67. btns = []
  68. for btn in buttons:
  69. if isinstance(btn, Mapping):
  70. assert 'value' in btn and 'label' in btn, 'actions item must have value and label key'
  71. elif isinstance(btn, list):
  72. assert len(btn) == 2, 'actions item format error'
  73. btn = dict(zip(('value', 'label'), btn))
  74. else:
  75. btn = dict(value=btn, label=btn)
  76. btns.append(btn)
  77. return btns
  78. def td_buttons(buttons, onclick, save=None, mutex_mode=False):
  79. """
  80. 在表格中显示一组按钮
  81. 参数含义同 buttons 函数
  82. :return:
  83. """
  84. btns = _format_button(buttons)
  85. callback_id = register_callback(onclick, save, mutex_mode)
  86. tpl = '<button type="button" value="{value}" class="btn btn-primary btn-sm" ' \
  87. 'onclick="WebIO.DisplayAreaButtonOnClick(this, \'%s\')">{label}</button>' % callback_id
  88. btns_html = [tpl.format(**b) for b in btns]
  89. return ' '.join(btns_html)
  90. def buttons(buttons, onclick, small=False, save=None, mutex_mode=False):
  91. """
  92. 显示一组按钮
  93. :param buttons: button列表, button可用形式: value 只能为字符串
  94. {value:, label:, }
  95. (value, label,)
  96. value 单值,label等于value
  97. :param onclick: CallBack(btn_value, save) CallBack can be generator function or coroutine function
  98. :param save:
  99. :param mutex_mode: 互斥模式,回调在运行过程中,无法响应同一回调,仅当onclick为协程函数时有效
  100. :return:
  101. """
  102. btns = _format_button(buttons)
  103. callback_id = register_callback(onclick, save, mutex_mode)
  104. send_msg('output', dict(type='buttons', callback_id=callback_id, buttons=btns, small=small))
  105. def put_file(name, content):
  106. """
  107. :param name: file name
  108. :param content: bytes-like object
  109. :return:
  110. """
  111. content = b64encode(content).decode('ascii')
  112. send_msg('output', dict(type='file', name=name, content=content))