How to shut down python server

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 02:16:20

问题


Used this code to run a python server:

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()

How to make it stop?


回答1:


Your question is ambiguous - if your running the server via shell i.e. python myscript.py, simply press crtl + C.

If you want to close it elegantly using code, you must decide on some condition, or point, or exception to call it shutdown. You can add a block and call httpd.shutdown() - as HttpServer itself is a SocketServer.TCPSServer subclass:

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.

So the BaseServer has a method shutdown(), hence being a subclass HttpServer has it too.

for example:

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()

Helpful relevant question -

  • How do I shutdown an HTTPServer from inside a request handler in Python?
  • How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?



回答2:


Just use ^C (control+c) to shut down python server.



来源:https://stackoverflow.com/questions/42763311/how-to-shut-down-python-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!