Realtime data update to streamlit from python variable

Summary

I am trying to understand how to update realtime data in streamlit app.Looping through the numbers 1 to 100, display the number along with number * 10. But streamlit always shows number as 1.

Steps to reproduce

Code snippet:

mport threading
import streamlit as st
import time

global val, multiply


def test_run():
    global val, multiply
    for x in range(1, 100):
        val = x
        multiply = val * 10
        print(val)
        time.sleep(1)
    return val, multiply


threading.Thread(target=test_run).start()

# dashboard title
st.title("Stramlit Learning")

# creating a single-element container.
placeholder = st.empty()

with placeholder.container():
    col1, col2 = st.columns(2)
    col1.metric(label="Current Value", value=val)
    col2.metric(label="Multiply by 10 ", value=multiply)

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

You can use queue in this case to capture the values from data generator. You can then show the values in metric.

Here is a demo based from your code.

import threading
import streamlit as st
import time
import queue


q = queue.Queue()


def test_run():
    for x in range(1, 100):
        time.sleep(1)
        val = x
        multiply = val * 10        
        q.put((val, multiply))


is_exit_target_if_main_exits = True
threading.Thread(
    target=test_run,
    daemon=is_exit_target_if_main_exits).start()

# dashboard title
st.title("Streamlit Learning")

# creating a single-element container.
placeholder = st.empty()

# Exit loop if we will not receive data within timeoutsec.
timeoutsec = 30

# Simulate data from test_run() in placeholder.
while True:
    try:
        val, multiply = q.get(block=True, timeout=timeoutsec)
    except queue.Empty:
        break  # exit loop
    else:
        with placeholder.container():
            col1, col2 = st.columns(2)
            col1.metric(label="Current Value", value=val)
            col2.metric(label="Multiply by 10 ", value=multiply)
            q.task_done()
1 Like

Thanks @ferdy