停止Python脚本的执行

3

在阅读了这个问题这个问题之后,我写下了这个问题。

当按下一个按钮时,我想停止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仅适用于该函数,而不适用于整个程序。有什么建议吗?

你试过使用 turtle.bye 而不是你的 stop_program 函数吗?https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.bye - Andrew
@Andrew:它存在,但有一些错误(似乎是因为它在执行其他操作时出现了问题)。 - Leos313
2
我能看到你在 while True: 下面写了什么吗?你有在任何地方使用 except:\n 吗? - user2201041
我在想如果有一个裸的 except:(而不是 except Exception),它会解释为什么你没有完全退出。这真的很奇怪。 - user2201041
2
我已经找到了为什么会发生这种情况的原因:“由于exit()最终“只是”引发异常,因此仅在从主线程调用时才会退出进程,并且异常不会被拦截。” 我正在调查以找到一个“干净”的解决方案(有关sys模块文档的详细信息)。 - Leos313
显示剩余3条评论
2个回答

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

对我来说,这似乎很好用,试一下吧。


turtle.mainloop()的定义在哪里?我应该在哪里插入我的指令?我会尝试在谷歌上搜索更多信息。 - Leos313
它已经内置在turtle中,https://docs.python.org/3.1/library/turtle.html#turtle.mainloop - mikeg

-1
尝试使用: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()

当然可以。从sys导入exit后,只需要写exit而不是sys.exit(),这两者是等价的,不是吗? - Leos313
导入sys,然后使用sys.exit()。对我来说运作得很好。使用了mikeg的代码,但根据我的建议进行了修改。 - Ticu Bogdan
你试过我在问题中写的代码了吗?它能正常工作吗?真的吗? - Leos313
它不起作用。请尝试在问题中提供的代码。 - Leos313
我编辑了我的解决方案,向您展示了对我有效的内容。请看一下并告诉我。 - Ticu Bogdan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接