正确终止在线程中运行的烧瓶Web应用程序

时间:2018-03-24 21:08:13

标签: python multithreading flask kill-process

如何正确终止在单独的线程中启动的烧瓶Web应用程序?我发现一个不完整的answer,如何做到这一点尚不清楚。下面的脚本启动一个线程,然后启动一个烧瓶应用程序。当我按 CTRL + C 时,某些内容未被终止且脚本永远不会停止。最好在except KeyboardInterrupt:之后添加正确终止appthread_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

1 个答案:

答案 0 :(得分:4)

不要join子线程。请改用setDaemon

from flask import Flask
import time
import threading


def thread_webAPP():
    app = Flask(__name__)

    @app.route("/")
    def nothing():
        return "Hello World!"

    app.run(debug=True, use_reloader=False)


t_webApp = threading.Thread(name='Web App', target=thread_webAPP)
t_webApp.setDaemon(True)
t_webApp.start()

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    print("exiting")
    exit(0)
对于子线程,

daemon表示如果您尝试停止主线程,主线程将不会等到此守护程序子线程完成其作业。在这种情况下,所有子线程将自动连接,主线程将立即成功停止。

更多信息是here

相关问题