【问题标题】:Python server will not terminate on Ctrl+C after a request has come in请求进入后,Python 服务器不会在 Ctrl+C 上终止
【发布时间】:2018-10-16 17:41:31
【问题描述】:

我正在涉足 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)

【问题讨论】:

  • 你说的和这个不一样吗? $ python3 test.py serve Starting web server. Press Ctrl+C to exit! ^CShutting down... $ 因为我用Ctrl+C 时好像关机了。
  • 当您发送 Ctrl-C 时,服务器会收到 KeyboardInterrupt 异常,但它可能会卡在 socket.accept() 调用中(这是一个不可中断的 IO 等待状态)。您可以简单地连接到套接字(例如,使用像 telnetnetcat 这样的工具)来打破等待状态。在更健壮的环境中,您将使用应该处理此类事情的专用 WSGI 服务器。
  • @agaidis 仅在没有请求进入时才有效。尝试实际访问 localhost:8080 并查看它在第一次访问后不会退出

标签: python http server


【解决方案1】:

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

【讨论】:

  • 这并不能真正回答问题。如果您有其他问题,可以点击 提问。要在此问题有新答案时收到通知,您可以follow this question。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
猜你喜欢
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2020-01-12
  • 1970-01-01
相关资源
最近更新 更多