6631

How do I shutdown an HTTPServer from inside a request handler in Python?

How do I shutdown this server when I receive the StopIteration exception? sys.exit() does not work.

#!/usr/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer PORT_NUMBER = 2000 from itertools import islice filename = 'data/all.txt' file = open(filename, 'r') lines_gen = islice(file, None) class MyHandler(BaseHTTPRequestHandler): def do_GET(self): global lines_gen self.send_response(200) self.send_header('Content-type','text/plain') self.end_headers() try: for i in range(10): next_line = lines_gen.next() self.wfile.write(next_line) except StopIteration: # return response and shutdown the server # ????? return try: server = HTTPServer(('', PORT_NUMBER), MyHandler) print('Started httpserver on port ' , PORT_NUMBER) server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close()

Answer1:

Just call shutdown() in a second thread.

# return response and shutdown the server import threading assassin = threading.Thread(target=server.shutdown) assassin.daemon = True assassin.start()

Recommend

  • Python. nwise numpy array iteration
  • What causes the NZEC (Non Zero Exit Code) error in my Sums in a Triangle solution?
  • Python get N elements from a list at a time using lambda
  • Is there a better way to do an “unravel” function in python?
  • pip in virtualenv gets ConnectTimeoutError
  • Run multiple queries from 1 SQL file showing result in multiple tables
  • how to upload multiple files in c# windows application
  • Installed module is empty
  • Swing - Get new component under mouseReleased
  • Refering to the class itself from within a class mehod in Objective C
  • How to install a .deb file on a jailbroken iphone programmatically?
  • Handling un-mapped Rest path
  • Java: can you cast Class into a specific interface?
  • FileReader+canvas image loading problem
  • Using jQuery closest() method with class selector
  • Insert into database using onclick function
  • Can I display google adwords (AdView) in javafx on android
  • Align navbar back button on right side
  • How to add date and time under each post in guestbook in google app engine
  • How to set/get protobuf's extension field in Go?
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • Validaiting emails with Net.Mail MailAddress
  • Can I make an Android app that runs a web view in Chrome 39?
  • sending/ receiving email in Java
  • Web-crawler for facebook in python
  • Akka Routing: Reply's send to router ends up as dead letters
  • Cannot Parse HTML Data Using Android / JSOUP
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • coudnt use logback because of log4j
  • Java static initializers and reflection
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • unknown Exception android
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • reshape alternating columns in less time and using less memory
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app