魔法命令是Streamlit中的一个功能,它允许你几乎可以编写任何内容(markdown、数据、图表),而无需输入明确的命令。只需将你想要显示的内容放在代码的单独一行上,它就会出现在你的应用程序中。以下是一个示例:

# Draw a title and some text to the app: ''' # This is the document title This is some _markdown_. ''' import pandas as pd df = pd.DataFrame({'col1': [1,2,3]}) df # 👈 Draw the dataframe x = 10 'x', x # 👈 Draw the string 'x' and then the value of x # Also works with most supported chart types import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) fig # 👈 Draw a Matplotlib chart

每当Streamlit看到单独一行的变量或字面值时,它会自动使用st.write将其写入你的应用程序中(你稍后会学到这个)。

此外,magic足够智能,可以忽略文档字符串。也就是说,它会忽略文件和函数顶部的字符串。

如果您更喜欢更明确地调用 Streamlit 命令,您可以通过以下设置在 ~/.streamlit/config.toml 中关闭魔法功能:

[runner] magicEnabled = false
priority_high

重要

目前,Magic 仅在主 Python 应用程序文件中有效,而不在导入的文件中。有关问题的讨论,请参见 GitHub 问题 #288。

了解st.writemagic命令是什么以及如何使用它们。

forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。