Stop or Cancel button

Is there any mechanism is to cancel or stop a running process using a button? in my application, I want to start a process and then stop it using another button. I tried so many ways but couldn’t make it work.

import streamlit as st
import time
from SessionState import get
from multiprocessing import Process

st.sidebar.title("controls")
start = st.sidebar.button("start")
stop = st.sidebar.button("stop")


session_state = get(a=0)


def working():
    print("working started")
    session_state.a = 2
    for i in range(100):
        time.sleep(1)
        print(session_state.a)
        if session_state.a == 1:
            break

p = Process(target=working)
global pid
if start:
    print("start")
    p.start()
    pid = p.pid
    print("in start", pid)

if stop:
    print("stop")
    session_state.a = 1
    print("in stop", pid)

1 Like

Welcome to the forum, @rohola_zandie :wave:

I believe the code below does what you want:

from multiprocessing import Process
import streamlit as st
import SessionState
import time
import os
import signal

st.sidebar.title("Controls")
start = st.sidebar.button("Start")
stop = st.sidebar.button("Stop")

state = SessionState.get(pid=None)


def job():
    for _ in range(100):
        print("In progress")
        time.sleep(1)


if start:
    p = Process(target=job)
    p.start()
    state.pid = p.pid
    st.write("Started process with pid:", state.pid)

if stop:
    os.kill(state.pid, signal.SIGKILL)
    st.write("Stopped process with pid:", state.pid)
    state.pid = None

I’ve changed it a little bit, but the main idea is that you need to store the pid in the session state and only start a new process inside the start if condition.

Please let me know if you need any further clarification.

1 Like

Thanks it’s working!

My pleasure!

1 Like