在用Python做一个HTML帮助工具时,我想顺利退出程序,就像在谷歌浏览器上点击X按钮一样。但是,我遇到了一个问题。它询问我是否要终止程序,而不是自动执行。
我尝试使用 quit()、exit() 和 sys.exit()。所有人都做同样的事情。怎样才能让程序顺利退出?
请您参考如下方法:
正如评论中所建议的,您的问题应该只在 Python 的 IDLE 中被注意到,但在终端中执行时应该运行良好。然而,这段代码也应该在 IDLE 中杀死你的程序:
import os, signal
from time import sleep
print("I will sleep for 3 secs and shut down!")
sleep(3)
os.kill(os.getpid(), signal.SIGTERM)
这会向您的应用程序发送终止信号。
或者您可以调用 os 的 _exit 函数。 来自文档:
Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
