如何在 Dash Tab 中显示 python 脚本?

问题描述 投票:0回答:1

我一直在尝试在 Dash 中显示几个 .py 文件。目标是每个脚本有一个选项卡。脚本太长,无法逐行编码,也太长,无法仅对它们进行屏幕截图以显示为图像,无论如何,这都远非理想。

我尝试简单地使用 html.P 打印它们,但它们丢失了换行符。我已将它们转换为 html,希望 dash 可以以某种方式处理该代码。我找到了convert-html-to-dash 库,但它不起作用。我已将 html 转换为 json 并尝试将 json 字典作为数字发送到仪表板。所有这些方法似乎都还很遥远。

有人有在仪表板中共享 .py 代码的方法吗?

更新/附加信息:

我在这里找到了下面的代码:https://community.plotly.com/t/convert-html-to-dash-html-components/47328/4

我正在尝试将我的 html 版本的代码逐行读取到转换器函数中,但代码已过时。我该如何解决

AttributeError:'cython_function_or_method'对象没有属性'fromstring'

import ast
def convert_html_to_dash(html_code, dash_modules=None):
    """Convert standard html (as string) to Dash components.

    Looks into the list of dash_modules to find the right component (default to [html, dcc, dbc])."""
    from lxml.etree import ElementTree

    if dash_modules is None:
        from dash import html
        from dash import dcc

        dash_modules = [html, dcc]
        try:
            import dash_bootstrap_components as dbc

            dash_modules.append(dbc)
        except ImportError:
            pass

    def find_component(name):
        for module in dash_modules:
            try:
                return getattr(module, name)
            except AttributeError:
                pass
        raise AttributeError(f"Could not find a dash widget for '{name}'")

    def parse_css(css):
        """Convert a style in ccs format to dictionary accepted by Dash"""
        return {k: v for style in css.strip(";").split(";") for k, v in [style.split(":")]}

    def parse_value(v):
        try:
            return ast.literal_eval(v)
        except (SyntaxError, ValueError):
            return v

    parsers = {"style": parse_css, "id": lambda x: x}

    def _convert(elem):
        comp = find_component(elem.tag.capitalize())
        children = [_convert(child) for child in elem]
        if not children:
            children = elem.text
        attribs = elem.attrib.copy()
        if "class" in attribs:
            attribs["className"] = attribs.pop("class")
        attribs = {k: parsers.get(k, parse_value)(v) for k, v in attribs.items()}

        return comp(children=children, **attribs)

    et = ElementTree.fromstring(html_code)

    return _convert(et)


file1 = open('exits.txt', 'r')
file2 = open('exits_dash.py', 'w')

count = 0
for line in file1:
    count += 1
    line_out = convert_html_to_dash(line)
    file2.writelines(line)

file1.close()
file2.close()
python html json plotly-dash
1个回答
0
投票

为此有一个很好的 Mantine 组件。您可以在此处查看详细信息:Mantine 代码组件。例如:

import dash_mantine_components as dmc

dmc.Code(
    """from dash import Dash
import dash_mantine_components as dmc

app = Dash(__name__)

app.layout = dmc.Button("Settings")

if __name__ == "__main__":
    app.run_server(debug=True)""",
    block=True,
)

此外,Plotly 还提供了一种原生显示代码的方式: Plotly 代码组件

© www.soinside.com 2019 - 2024. All rights reserved.