Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3:How do I close connection opened by http.server?

I was using looking at the docs of http.server and ran the code:

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

Now I can't close the server running on port 8000 , How do I close it?

like image 556
Yashik Avatar asked Apr 11 '26 12:04

Yashik


2 Answers

You can use ^C (control+c) to shut down python server

or use httpd.shutdown() in the code to close it.

See the detailed answer at

https://stackoverflow.com/a/42763796/10241547

like image 182
Raj Sappidi Avatar answered Apr 14 '26 01:04

Raj Sappidi


The HTTPServer is a subclass of TCPServer class

When serve_forever() function is executed it periodically checks for the value of __shutdown_request variable. If its value becomes True, the serve_forever() function exits its main loop.

The shutdown() method sets that variable to True thus initiating loop break.

like image 41
leotrubach Avatar answered Apr 14 '26 01:04

leotrubach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!