Python在if命令中的任意点停止程序



我目前正在编写一个程序,该程序要求用户输入一些参数,然后按下按钮启动程序的主要部分。

按下启动按钮后,if循环执行命令的顺序(大约20(,然后停止。

我希望能够在代码执行过程中的任何时候使用单独的"停止"按钮停止这一命令序列,但我不确定如何停止。比起GUI语法,我更感兴趣的是一种实现这一点的方法。

感谢您的帮助。

示例代码:

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

您可以在任何时候使用循环并中断执行。如果您只想在步骤中进行一次传递,请在末尾添加最后一次打断。

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

您可以在循环中使用break语句。设置一个事件,当按下停止按钮时,它会触发一个特定的值,这个值会改变循环。以下的样品处理

stop = False
if stop_button_is_pressed:
stop = True
for a in b:
if stop == True:
break
print(a)
print("Stopped")

您可以随时使用multiprocessing.Processterminate()进程/函数my_process_function()。。。将其作为脚本运行以获得输出。

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()

最新更新