2025年6月6日 星期五

Streamlit 學習筆記 : 顯示程式碼內容與說明資訊

本篇旨在測試 Streamlit 的顯示程式碼函式 st.echo() 與說明資訊函式 st.help() 的功能, 這兩個函式在製作教學展示的應用程式時非常有用.

本系列所有測試文章參考 : 



1. 顯示程式碼 st.echo() :

st.echo() 用來顯示應用程式的執行結果, 同時也顯示對應的程式碼, 常用來做教學展示, 讓使用者能同時看到原始碼 + 執行結果, 可讓展示變得更直觀與有互動性, 協助使用者理解運作邏輯. Streamlit 的另一個函式 st.code() 也可以在頁面上顯示程式碼, 但那程式碼只是被靜態顯示而已, 並不會在應用程式中被執行. 

參數結構如下 : 

st.echo(code_location="above")

可選參數 code_location 用來控制程式碼顯示在執行結果的上方或下方, 其值有 "above" (預設) 或 "below", 此函式無傳回值, 使用時必須搭配 with 語法 : 

with st.echo():
    # 要顯示的程式碼

with 區塊內的程式碼會顯示在執行結果的上方或下方. 例如 : 


測試 1-1 : 預設的 st.echo() 效果 [看原始碼]   

# st-echo-test-1.py
import streamlit as st

st.subheader('st.echo() 範例')
with st.echo():
    st.write('位於 with st.echo() 區塊內')
    x=10
    y=20
    st.write(f'x + y = {x + y}')

結果如下 : 




可見程式碼預設顯示在執行結果上方. 下面範例則是用 code_location="below" 將程式碼顯示在執行結果下方 : 


測試 1-2 : st.echo( code_location="below") 效果 [看原始碼  

# st-echo-test-2.py
import streamlit as st

st.subheader('st.echo(code_location="below") 範例')
with st.echo(code_location='below'):
    st.write('位於 with st.echo() 區塊內')
    x=10
    y=20
    st.write(f'x + y = {x + y}')

結果如下 : 




可見程式碼顯示在執行結果下方了. 


2. 顯示程式碼 st.help() :

st.help() 用來顯示 Python 物件 (例如函數, 類別, 模組, 實例等) 說明資訊, 其功能類似 Python 的 help() 函式, 它會以易讀的格式在網頁介面上即時展示指定物件的名稱, 型別, 值, 簽名, docstring (說明文件), 成員變數與方法等資訊, 適合用於教學, 除錯或快速查閱物件細節. 

參數結構如下 : 

st.help(obj)

必要參數 obj 為要查詢的物件, 可以是函式, 模組, 類別, 方法, 變數等 (支援 Python 內建與自定義物件, 以及第三方模組與套件), 此函式無傳回值. 

例如顯示 Python 內建函式的說明  : 


測試 2-1 : 顯示 Python 內建函式的說明 [看原始碼]   

# st-help-test-1.py
import streamlit as st

st.subheader('st.help(obj) 範例')
st.help(len)
st.help(max)

結果如下 : 




下面是傳入 Python 內建模組的範例 : 


測試 2-2 : 顯示 Python 內建模組的說明 [看原始碼]   

# st-help-test-2.py
import streamlit as st
import datetime

st.subheader('st.help(obj) 範例')
st.help(datetime)

結果如下 : 




下面是傳入類別 (class) 與方法 (method) 的範例 : 


測試 2-3 : 顯示類別與方法的說明 [看原始碼]   

# st-help-test-3.py
import streamlit as st

st.subheader('st.help(obj) 範例')
st.help(list)
st.help(str.upper)

結果如下 : 




下面是傳入第三方套件 (Pandas) 的範例 : 


測試 2-4 : 顯示第三方套件 Pandas 的說明 [看原始碼  

# st-help-test-4.py
import streamlit as st
import pandas as pd

st.subheader('st.help(obj) 範例')
st.help(pd)

結果如下 :




下面是傳入 Streamlit 的 st.slider 函式的範例 : 


測試 2-5 : 顯示 Streamlit 的 st.slider() 的說明 [看原始碼]   

# st-help-test-5.py
import streamlit as st

st.subheader('st.help(obj) 範例')
st.help(st.slider)

結果如下 : 



沒有留言 :