收到请求后,Python服务器不会在Ctrl + C上终止

时间:2018-10-16 17:41:31

标签: 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)

0 个答案:

没有答案