Pythonw、pyw 和 arg,/B 不会使 python 的 http 服务器在后台运行

问题描述 投票:0回答:2

我已经尝试了标题中的每种方法来在后台运行它,但以下是我尝试使用它们时遇到的问题:

pythonw 和 pyw:服务器无法工作,转到 localhost:8000 错误并显示 ERR_EMPTY_RESPONSE。
& arg 和 START/B:不在后台启动脚本,而是输出服务器日志

所以现在我不知道如何在后台运行这个脚本。

python-3.x windows background-process httpserver
2个回答
3
投票

使用

pythonw
,应该有助于显式地将
stdout
stderr
重定向到文件 - 也许这种行为在某种程度上与here描述的问题有关(尽管这似乎是 Python 2.7 特有的)。不通过将输出重定向到
os.devnull
来捕获输出似乎也可行。

以下脚本为我生成了一个带有

pythonw
的最小工作服务器示例(使用 Python 3.7.9):

import http.server
import os
import sys


if __name__ == "__main__":

    sys.stdout = sys.stderr = open(os.devnull, "w")

    httpd = http.server.HTTPServer(("localhost", 8000), http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

0
投票

我找到了一个在后台启动http服务器的好解决方案。

这个解决方案有点破解,但它在我的计算机上运行得很好。

在单独的

subprocess
文件中使用
.pyw
模块来启动存储在
.py
文件中的服务器脚本。

启动.pyw

import subprocess

subprocess.run(
            ["python.exe", "http_server.py"], 
            creationflags=0x08000000,         # use this "non creation window" flag if 
                                              # working with pyinstaller
)

http_server.py

import http.server

# your code

if __name__ == "__main__":
    httpd = http.server.HTTPServer(("localhost", 8000), 
            http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

现在,您应该使用

launch.pyw
脚本启动服务器。

© www.soinside.com 2019 - 2024. All rights reserved.