繁体   English   中英

停止执行Python脚本

[英]Stopping the execution of Python script

在阅读了这个问题另一个问题之后,我已经写了这个问题。 我想在按下按钮时停止执行Python脚本。 这里的代码:

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

如果我按下按钮“ q”(偶数时间),则输出为:

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

即每次我按一行。 这意味着exit适用于该功能,而不适用于整个程序。 有什么建议吗?

不要使用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()

这对我来说似乎很好,请尝试一下。

尝试使用:sys.exit(),看看是否可行。 下面的代码为我工作。

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