如何正确终止在单独线程中启动的flask Web应用程序?我发现一个不完整的答案,不清楚如何操作。下面的脚本启动一个线程,该线程又启动了一个flask应用程序。当我按下CTRL+C时,某些内容没有被终止,脚本永远不会停止。希望在
except KeyboardInterrupt:
之后添加代码,以正确终止app
和thread_webAPP()
。我知道如何终止线程,但首先需要终止应用程序:def thread_webAPP():
app = Flask(__name__)
@app.route("/")
def nothing():
return "Hello World!"
app.run(debug=True, use_reloader=False)
# hope that after app.run() is terminated, it returns here, so this thread could exit
t_webApp = threading.Thread(name='Web App', target=thread_webAPP)
t_webApp.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("exiting")
# Here I need to kill the app.run() along with the thread_webAPP
t_webApp.setDaemon(True)
之后,它正常退出了。我希望它不会留下任何“幽灵”进程。谢谢。 - Nazarstop
,以确保线程以干净的方式结束。 - dhalfageme