简体   繁体   English

停止执行Python脚本

[英]Stopping the execution of Python script

I have written this question after reading this question and this other one . 在阅读了这个问题另一个问题之后,我已经写了这个问题。 I would like to stop the execution of a Python script when a button is pressed. 我想在按下按钮时停止执行Python脚本。 Here the code: 这里的代码:

import turtle
from sys import exit

def stop_program():
    print("exit function")
    exit(0) #raise SystemExit(0) gives the same result
    print("after the exit function")

# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")

# Main function
while True:
    # Code: everything you want

If I press the button "q" (even muliple time) the output is: 如果我按下按钮“ q”(偶数时间),则输出为:

exit function
exit function
exit function
exit function
exit function
exit function
exit function
...

ie one line every time I press. 即每次我按一行。 This means that the exit works for the function and not for the whole program. 这意味着exit适用于该功能,而不适用于整个程序。 Any suggestion? 有什么建议吗?

Dont use the while loop, use turtle.mainloop() 不要使用while循环,请使用turtle.mainloop()

import turtle
from sys import exit

def stop_program():
    print("exit function")
    exit(0) #raise SystemExit(0) gives the same result
    print("after the exit function")

# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")


turtle.mainloop()

That seems to work fine for me, give it a try. 这对我来说似乎很好,请尝试一下。

Try to use: sys.exit(), see if that works. 尝试使用:sys.exit(),看看是否可行。 Below code worked for me. 下面的代码为我工作。

import turtle
import sys

def stop_program():
 print("exit function")
 sys.exit() #raise SystemExit(0) gives the same result
 print("after the exit function")


 # Create keyboard binding
 turtle.listen()
 turtle.onkey(stop_program, "q")
 turtle.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM