gpt4 book ai didi

python - 如何关闭python服务器

转载 作者:行者123 更新时间:2023-11-28 21:43:04 24 4
gpt4 key购买 nike

使用此代码运行 python 服务器:

import os
from http.server import SimpleHTTPRequestHandler, HTTPServer

os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27')
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
httpd.serve_forever()

如何让它停止?

最佳答案

您的问题不明确 - 如果您通过 shell 即 python myscript.py 运行服务器,只需按 crtl + C

如果你想用代码优雅地关闭它,你必须决定一些条件,或者点,或者异常来调用它关闭。您可以添加一个 block 并调用 httpd.shutdown() - 作为 HttpServer 本身就是一个 SocketServer.TCPSServer 子类:

The first class, HTTPServer, is a SocketServer.TCPServer subclass, and therefore implements the SocketServer.BaseServer interface. It creates and listens at the HTTP socket, dispatching the requests to a handler.

所以 BaseServer 有一个方法 shutdown() ,因此作为 HttpServer 的子类也有它。

例如:

import os
from http.server import SimpleHTTPRequestHandler, HTTPServer

os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27')
server_address = ('', 8000)
try:
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
httpd.serve_forever()
except Exception:
httpd.shutdown()

有用的相关问题-

关于python - 如何关闭python服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com