如何根据用户答案在Streamlit中显示代码?

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

我正在尝试使用Streamlit为图书馆创建一个教程。我的总体思路是逐步介绍不同的功能和类,并与基于用户的Input一起解释它们,因此对于初学者而言,所有内容都变得更加容易理解。但是,我之前已经为经验丰富的用户编写了5个教程,并希望通过在我的应用程序内调用它们并仅对其维护一次来重用某些代码。

此外,我还将遍历许多函数和类,例如配置文件示例。我是从字典中称呼他们

正如Streamlit提供的带有st.echo的选项来运行代码,然后显示它,我已经尝试过了。我也尝试过将python inspect Element与st.write一起使用。但是,st.echo仅显示函数名称,而st.write和inspect仅显示字符串。


display_code = st.radio("Would you like to display the code?", ("Yes", "No"))

    if display_code == "Yes":
        with st.echo():
            example_function_1()



    else:
        example_function_1()

基本上,我正在寻找一个传递函数的选项,并且基于用户输入,只需运行它或运行它并显示代码和注释即可。

因此,如果用户选择“是”,则输出为,同时还返回x,y。

def example_function_1():
     """ 
     This is and example functions that is now displayed. 
     """ 
     Some Magic
     return x, y 

如果用户选择否,则仅返回x,y

python inspect streamlit
2个回答
0
投票

您可以使用会话状态将用户输入传递到屏幕操作中。可以找到一个带有单选按钮的清晰示例here。一般来说,您需要使用st.write()完成此操作。一个带有滑块的简化示例:

import streamlit as st

x = st.slider('Select a value')
st.write(x, 'squared is', x * x)

您要找的内容并非完全可能,因为您必须在with st.echo()块中指定函数。您可以在这里看到它:

import inspect
import streamlit as st

radio = st.radio(label="", options=["Yes", "No"])

if radio == "Yes":
    with st.echo():
        def another_function():
            pass
        # Print and execute function
        another_function()
elif radio == "No":
    # another_function is out of scope here..
    another_function()

0
投票

这里是Streamlit的st.echo()的修改版,其中包括一个复选框:

import contextlib
import textwrap
import traceback

import streamlit as st
from streamlit import source_util


@contextlib.contextmanager
def maybe_echo():
    if not st.checkbox("Show Code"):
        yield
        return

    code = st.empty()
    try:
        frame = traceback.extract_stack()[-3]
        filename, start_line = frame.filename, frame.lineno

        yield

        frame = traceback.extract_stack()[-3]
        end_line = frame.lineno
        lines_to_display = []
        with source_util.open_python_file(filename) as source_file:
            source_lines = source_file.readlines()
            lines_to_display.extend(source_lines[start_line:end_line])
            initial_spaces = st._SPACES_RE.match(lines_to_display[0]).end()
            for line in source_lines[end_line:]:
                indentation = st._SPACES_RE.match(line).end()
                # The != 1 is because we want to allow '\n' between sections.
                if indentation != 1 and indentation < initial_spaces:
                    break
                lines_to_display.append(line)
        lines_to_display = textwrap.dedent("".join(lines_to_display))

        code.code(lines_to_display, "python")

    except FileNotFoundError as err:
        code.warning("Unable to display code. %s" % err)

您可以完全像使用st.echo一样使用它。例如:

with maybe_echo():
    some_computation = "Hello, world!"
    st.write(some_computation)
© www.soinside.com 2019 - 2024. All rights reserved.