python - 正确终止在线程中运行的 Flask Web 应用程序

标签 python multithreading flask kill-process

如何正确终止在单独线程中启动的 Flask Web 应用程序?我发现了一个不完整的 answer目前尚不清楚该怎么做。下面的脚本启动一个线程,该线程又启动一个 flask 应用程序。当我按下 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

最佳答案

不要加入子线程。使用 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 .

关于python - 正确终止在线程中运行的 Flask Web 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49469978/

相关文章:

python - 在FeatureUnion中绑定(bind)变压器的输出

python - 类方法属性TypeError : 'property' object is not iterable

android - System.nanoTime() 在 Android 中给出了错误的时间

python - ValueError : set_wakeup_fd only works in main thread on Windows on Python 3. 8 使用 Django 3.0.2 或 Flask 2.0.0

python - 执行Python代码时自动打开浏览器

python - 通过 HASH 搜索全局规则的 DSaaS Python 脚本

python - 使用 stem 切换身份时一般 SOCKS 服务器故障

sql-server - 调用 CLR 函数时出现 SecurityException 错误 "Revisited"

java - 检测方法的并发调用

python - PyCharm 自动导入无法正确导入