Reputation: 13
I currently have a program that I am working on that requires the user to input some parameters, and then press a button to start the main part of the program.
After the start button is pressed, the if loop executes a sequential order of commands (around 20) and then stops.
I want to be able to stop this sequence of commands at any time during the code using a separate 'stop' button, but I am not sure how. I am more interested in a method of doing this than GUI syntax.
Any help is appreciated.
Example code:
if (start_button_is_pressed):
#do thing a
#do thing b
#do thing c
...
#do thing z
# i want to be able to stop from any point a-z
Upvotes: 1
Views: 700
Reputation: 193
You could use multiprocessing.Process
to terminate()
the process/function my_process_function()
whenever you please... Run it as script to get outputs.
import multiprocessing
def my_process_function():
for i in range (100):
print(i)
time.sleep(1)
print("my_process end")
if __name__ == "__main__":
x = multiprocessing.Process(target=my_process_function())
x.start()
print("Stop thread?")
a=input()
if (a=="y"):
x.terminate()
Upvotes: 0
Reputation: 71
you can use a break statement inside the loop. Set an event such that when the stop button is pressed, it triggers a certain value and this value alters the loop. Sample process below
stop = False
if stop_button_is_pressed:
stop = True
for a in b:
if stop == True:
break
print(a)
print("Stopped")
Upvotes: 0
Reputation: 4127
You can use a loop and break execution at any point. If you want only a single pass through the steps, add a final break at the end.
jump_out = False
while not jump_out:
step_1()
if (jump_out):
break
step_2()
if (jump_out):
break
# and so on
step_n()
break # add unconditional break for single-pass execution
Upvotes: 1