【问题标题】:Stopping the execution of Python script停止执行 Python 脚本
【发布时间】:2019-01-04 14:18:25
【问题描述】:

我在阅读this questionthis other one 后写了这个问题。 我想在按下按钮时停止执行 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函数吗? docs.python.org/3.3/library/…
  • 现在尝试,但是,我写的应该可以工作。问题是:为什么它退出函数而不是脚本执行?这不是“回报”
  • @Andrew:它存在但有一些错误(似乎是因为它在中间执行了其他操作)
  • 我可以看看你在while True:下面有什么吗?你碰巧在任何地方做except:\n 吗?
  • 我找到了为什么会这样:“由于exit()最终“只”引发了一个异常,它只会在从主线程调用时退出进程,并且该异常不会被拦截。”。我正在调查以找到一个“干净”的解决方案(来自 sys 模块文档的详细信息)

标签: python python-3.x exit turtle-graphics


【解决方案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()

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

【讨论】:

【解决方案2】:

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

【讨论】:

  • 当然不行:from sys import exit 允许只写 exit 而不是 sys.exit()。是一样的,不是吗?
  • 导入 sys,然后使用 sys.exit()。它对我来说很好。上面使用了 mikeg 的代码,但根据我的建议对其进行了一些调整。
  • 您尝试过我在问题中编写的代码吗?它有效吗?真的吗?
  • 它不起作用。请尝试问题中的代码
  • 我编辑了我的解决方案,向您展示什么对我有用。看看,让我知道。
猜你喜欢
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多