1

我正在尝试为带有 Streamlit 的库创建教程。我的总体想法是遍历不同的函数和类,并与基于用户的输入一起解释它们,这样对于初学者来说一切都变得更容易理解了。但是,我之前为更有经验的用户编写了 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

4

2 回答 2

2

这是 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)
于 2020-03-04T20:50:54.543 回答
0

您可以使用会话状态将用户输入传递给屏幕操作。可以在此处找到带有单选按钮的清晰示例。一般来说,您需要使用 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()
于 2020-02-26T10:49:38.797 回答