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