Skip to content Skip to sidebar Skip to footer

Run Server Alongside Infinite Loop In Python

I have the following code: #!/usr/bin/python import StringIO import subprocess import os import time from datetime import datetime from PIL import Image # Original code written by

Solution 1:

This isn't a small question. Your best bet is to work through some python threading tutorials such as this one: http://www.tutorialspoint.com/python/python_multithreading.htm (found via google)

Solution 2:

Try taking the webserver, and running it on a background thread so that calling "serve_forever()" does not block the main thread's "while True:" loop. Replace the existing call to httpd.serve_forever() with something like:

import threading
class WebThread(threading.Thread):
    def run(self):
        httpd = SocketServer.TCPServer(("", 8080), MyHandler)
        httpd.serve_forever()

WebThread().start()

Make sure that chunk of code runs before the "while (True):" loop, and you should have both the webserver loop and the main thread loop running.

Keep in mind that having multiple threads can get complicated. What happens when two threads access the same resource at the same time? As Velox mentioned in another answer, it is worthwhile to learn more about threading.

Solution 3:

I can illustrate a simple example using multi-threading.

from http.server import BaseHTTPRequestHandler, HTTPServer
import concurrent.futures
import logging
import time

hostName = "localhost"
serverPort = 5001classMyServer(BaseHTTPRequestHandler):
    defdo_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>python3 http server</title><body>", "utf-8"))  

defserverThread():
    webServer = HTTPServer((hostName, serverPort), MyServer)
    logging.info("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except :
        pass

    webServer.server_close()
    logging.info("Server stopped.")
  
deflogThread():
    whileTrue:
        time.sleep(2.0)
        logging.info('hi from log thread')

if __name__ == "__main__":        

    logging.basicConfig(level=logging.INFO)
       
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        # Run Server
        executor.submit(serverThread)
        # Run A Parallel Thread
        executor.submit(logThread)

Here we have two threads : A server and Another parallel Thread which logs a line every 2 seconds.

You have to define code corresponding to each thread in separate functions, and submit it to the concurrent.futures Thread Pool.

Btw, I have not done study of how efficient it is to run a server this way.

Post a Comment for "Run Server Alongside Infinite Loop In Python"