请求进入后,Python 服务器不会按 Ctrl+C 终止

标签 python http server

我正在涉足 Python 和 HTTP。创建了这个我使用 python cli.py serve 运行的简单服务器脚本。服务器启动并工作,但键盘中断 Ctrl+C 仅在下一页刷新时进入低谷,而不是当我在终端中实际按下 Ctrl+C 时。对此有任何修复吗?注意:当没有请求进来时立即工作。

from http.server import HTTPServer, BaseHTTPRequestHandler
import sys, signal

commands = ["serve"]

class Server(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            self.path = "/index.html"
        self.send_response(200)
        self.end_headers()
        self.wfile.write(bytes("Tere, maailm!!",'utf-8'))


if len(sys.argv) > 1 and sys.argv[1] in commands:
    index = commands.index(sys.argv[1])
    if index == 0: # serve command
        print("Starting web server. Press Ctrl+C to exit!")
        httpd = HTTPServer(("localhost", 8080), Server)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("Shutting down...")
            httpd.socket.close()
            sys.exit(0)
else:
    print("Usage: python tab.py [command], where [command] is any of", commands)

最佳答案

同样的问题... 我发现了 ThreadingHTTPServer,它可以工作(而不是 HTTPServer)

关于请求进入后,Python 服务器不会按 Ctrl+C 终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52841147/

相关文章:

java - 使用 Java 从 Microsoft 邮件 Exchange 服务器读取带有附件的邮件

python - 如何迭代 Pandas 数据框并创建新列

python - 如何从不同的进程修改 TextView ?

python - 在父类中实现继承方法

java - 为什么我看到的页面与维基百科不同?

http - 谷歌说 : Sort parameters in URL problematic

python - "<method> takes no arguments (1 given)"但我没有给

java - 使用 HttpUrlConnection 时如何从 CookieManager 设置 cookie?

Python http服务器-无法读取cookie

java - 在 Eclipse 启动时启动 Tomcat?