【发布时间】: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 等待状态)。您可以简单地连接到套接字(例如,使用像telnet或netcat这样的工具)来打破等待状态。在更健壮的环境中,您将使用应该处理此类事情的专用 WSGI 服务器。 -
@agaidis 仅在没有请求进入时才有效。尝试实际访问 localhost:8080 并查看它在第一次访问后不会退出