首页 > 解决方案 > Flask 导致父进程中的代码被执行两次

问题描述

我的 Python 程序在子进程上创建了一个烧瓶服务器。但是,父进程中的剩余代码随后会执行两次。谁能向我解释为什么会这样?

资源:

from multiprocessing import Process
from flask import Flask

class Server():
    def __init__(self):
        app = Flask(__name__)
        app.run(debug=True)
        print("This code is executed twice after a KeyboardInterrupt")

def main():
    p_server = Process(target=Server)
    p_server.start()

    print("This code in parent process is executed twice")

if __name__ == "__main__":
    main()

输出:

This code in parent process is executed twice
 * Serving Flask app "bug" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
This code in parent process is executed twice
 * Debugger is active!
 * Debugger PIN: 195-233-949
^CError in atexit._run_exitfuncs:
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
Traceback (most recent call last):
  File "/Users/myname/opt/anaconda3/envs/FYP2/lib/python3.7/multiprocessing/popen_fork.py", line 28, in poll
  File "/Users/myname/opt/anaconda3/envs/FYP2/lib/python3.7/multiprocessing/popen_fork.py", line 28, in poll
This code is executed twice after a KeyboardInterrupt
    pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
    pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
(FYP2) MyNames-MacBook-Pro:MyRepo myname$ This code is executed twice after a KeyboardInterrupt

标签: pythonflaskanacondamultiprocessingpython-multiprocessing

解决方案


推荐阅读