如何在 Streamlit 中使用 ZeroMQ

在 streamlit 中使用 ZMQ 并不简单,因为整个文件会被执行多次。所以你需要确保 context、socket 等只创建一次。

技巧是使用 @st.cache_resource 缓存 context 和 socket。这是一个示例:

streamlit_zmq_example.py
#!/usr/bin/env python3
import zmq
import json
import streamlit as st

# Set up ZMQ PUB socket
@st.cache_resource
def init_zmq():
    print("Initializing ZMQ")
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:15629")
    return context, socket
# Create context and socket, or use cached one
context,socket = init_zmq()

st.title('My streamlit ZMQ test')

# Create button
my_button = st.toggle('My button')

# Save button
if st.button('Save'):
    st.write('Button clicked!')
    message = json.dumps({
        'my_button': all_motors_on,
    })
    print(f"Sending message: {message}")
    socket.send_string(message)

Check out similar posts by category: ZeroMQ, Python