运行Flask时Python控制台无法打印输出的问题求助
Flask线程导致命令行输出失效的解决方案
我正在开发一个带管理控制台和前端的Python任务管理器网站,原本一切正常,但加入WebManager_Main.py的Flask代码后,CommandLine_Output.py里的控制台打印功能就失效了。两者运行在不同线程(代码见main.py),试过刷新缓冲区、用日志、禁用Flask打印等方法,都没恢复,求解决。
相关代码
Main.py
# Startup and import # import libraries import threading import time # import files import CommandLine_Handler as clh import DataBaseHandler_Main as DBHM import WebManager_main as WBM import Error_Handler as eh import Mailbox as mb # Startup mb.run_Main = True mb.run_Interface = True mb.run_Database = True mb.run_WebApp = True mb.loop_Counter = 0 cmdInterface = None dataBaseCreate = None WebAppManager = None # Run Loop while mb.run_Main == True: if mb.run_Interface == True: try: if cmdInterface == None: cmdInterface = threading.Thread(target = clh.interface) cmdInterface.daemon = True cmdInterface.start() else: if not cmdInterface.is_alive(): cmdInterface = threading.Thread(target = clh.interface) cmdInterface.daemon = True cmdInterface.start() except: eh.error("m-rl1") if mb.run_Database == True: try: if dataBaseCreate == None: dataBaseCreate = threading.Thread(target = DBHM.creator) dataBaseCreate.daemon = True dataBaseCreate.start() else: if not dataBaseCreate.is_alive(): dataBaseCreate = threading.Thread(target = DBHM.creator) dataBaseCreate.daemon = True dataBaseCreate.start() except: eh.error("m-rl2") if mb.run_WebApp == True: try: if WebAppManager == None: WebAppManager = threading.Thread(target = DBHM.creator) WebAppManager.daemon = True WebAppManager.start() else: if not WebAppManager.is_alive(): WebAppManager = threading.Thread(target = WBM) WebAppManager.daemon = True WebAppManager.start() except: eh.error("m-rl3") mb.loop_Counter += 1 time.sleep(0.5)
CommandLine_Output.py
import os import sys import pwinput as pIN import logging def output(input): print(input, flush=True) # logger = logging.getLogger('werkzeug') # logger.info(input) def uInput(prompt): userInput = input(prompt) return userInput def passInput(prompt): #userInput = pIN.pwinput(prompt=prompt, mask = '*') userInput = input(prompt) return userInput def clear(): os.system("cls" if os.name == "nt" else "clear") #os.system("cls")
WebManager_Main.py
from flask import Flask, render_template #this is the library responsible for the hosting of the Web app webApp = Flask(__name__) @webApp.route("/") def index(): return render_template("index.html") if __name__ == "WebManager_main": webApp.run(port=8080, debug = True)
问题分析与修复方案
1. 先修正main.py的WebApp线程错误
你在启动WebApp线程时犯了两个低级错误:
- 第一次启动时,
target写的是DBHM.creator(数据库进程),根本没启动Flask - 线程重启时,
target直接写WBM(模块对象),不是可执行的函数
同时Flask的debug=True会自动重启进程,直接劫持标准输出,必须关闭并禁用重载器。修改后的WebApp线程代码:
if mb.run_WebApp == True: try: if WebAppManager == None: # 正确指向Flask的run方法,关闭debug并禁用重载器 WebAppManager = threading.Thread( target=WBM.webApp.run, kwargs={"port":8080, "debug":False, "use_reloader":False} ) WebAppManager.daemon = True WebAppManager.start() else: if not WebAppManager.is_alive(): WebAppManager = threading.Thread( target=WBM.webApp.run, kwargs={"port":8080, "debug":False, "use_reloader":False} ) WebAppManager.daemon = True WebAppManager.start() except: eh.error("m-rl3")
2. 调整WebManager_Main.py的启动逻辑
原代码的启动判断写错了,改成只有直接运行该文件时才启动Flask,避免导入时自动执行:
from flask import Flask, render_template webApp = Flask(__name__) @webApp.route("/") def index(): return render_template("index.html") # 修正启动判断 if __name__ == "__main__": webApp.run(port=8080, debug=True)
3. 加固命令行输出稳定性
把CommandLine_Output.py的output函数改成明确指向标准输出,同时避免参数名和内置函数冲突:
import os import sys import pwinput as pIN import logging def output(input_str): # 明确指定输出到stdout,强制刷新 print(input_str, file=sys.stdout, flush=True) def uInput(prompt): userInput = input(prompt) return userInput def passInput(prompt): #userInput = pIN.pwinput(prompt=prompt, mask = '*') userInput = input(prompt) return userInput def clear(): os.system("cls" if os.name == "nt" else "clear")
核心原因总结
- Flask的debug模式和自动重载器会创建新进程,直接劫持原线程的标准输出
main.py中WebApp线程的目标函数设置错误,导致启动的不是Flask服务- 多线程环境下,必须明确指定输出流并强制刷新缓冲区
内容的提问来源于stack exchange,提问作者PyOrion
相关产品推荐
相关产品推荐

