简体   繁体   English

Python Flask 脚本在作为 .pyw 文件运行时自动关闭(包括解决方法)

[英]Python Flask script auto-closes when run as .pyw file (workaround included)

Problem问题

I've created a basic python script, using flask to render an HTML page.我已经创建了一个基本的 python 脚本,使用 Flask 来呈现一个 HTML 页面。 On Windows 10, the script works perfectly as a *.py file, but when run as a *.pyw file, the page is not rendered.在 Windows 10 上,该脚本作为*.py文件完美运行,但当作为*.pyw文件运行时,不会呈现页面。

In Task Manager, instances of python are opened and closed within seconds after running the script as *.pyw .在任务管理器中,python 的实例在以*.pyw运行脚本后几秒钟内打开和关闭。


Code代码

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=80)

Workaround解决方法

Run the *.py version with the following lines added to the code:运行*.py版本,并将以下几行添加到代码中:

import ctypes
...
...
...
if __name__ == '__main__':
  cytypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  app.run(debug=True, host="0.0.0.0", port=80)

Code above hides the console, and starts the flask app successfully.上面的代码隐藏了控制台,并成功启动了 Flask 应用程序。


However, I am still interested in an explanation as to why the *.pyw method won't work, if anyone has an idea.但是,如果有人有想法,我仍然对解释为什么*.pyw方法不起作用感兴趣。

.pyw-files would ran on pythonw.exe rather than python.exe . .pyw-files 将在pythonw.exe而不是python.exe The difference is, that pythonw.exe does not run in a console by default and runs asynchronous.不同之处在于, pythonw.exe默认不在控制台中运行, pythonw.exe异步运行。 This would mean that flask starts and runs in the background untill everything else terminates.这意味着烧瓶在后台启动并运行,直到其他一切都终止。 Since you to not have anything else in your application, the programm ends directly.由于您的应用程序中没有其他任何内容,因此程序直接结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM