user3310334
user3310334

Reputation:

How to continue python script after server started?

I have a script like this:

import http.server


class JotterServer(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        message = "Howdy"
        self.wfile.write(bytes(message, 'utf-8'))
        return


def start_server():
    print('Starting jotter server...')
    server_address = ('127.0.0.1', 8000)
    httpd = http.server.HTTPServer(server_address, JotterServer)
    httpd.serve_forever()


if __name__ == '__main__':
    start_server()
    print("hi")

The last line never gets called. How do I keep running the code after the server is started?

Upvotes: 2

Views: 1795

Answers (3)

Siva Gnanam
Siva Gnanam

Reputation: 1012

The following program will start the server in a new thread and continue with the main thread. The main thread will print hi to console.

import http.server
import threading

class JotterServer(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200);

        self.send_header('Content-Type', 'text/plain')
        self.end_headers()

        message = "Howdy"
        self.wfile.write(bytes(message, 'utf-8'))
        return

def start_server():
    print('Starting jotter server...')

    server_address = ('127.0.0.1', 8080)
    httpd = http.server.HTTPServer(server_address, JotterServer)
    thread = threading.Thread(target=httpd.serve_forever)
    thread.start()

start_server()

print("hi")

Take special note not to put () at the end of http.server_forever since we refer to the function itself.

Upvotes: 4

baky
baky

Reputation: 681

I guess this is because of serve_forever

From python docs

serve_forever(poll_interval=0.5): Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. If you need to do periodic tasks, do them in another thread.

You should probably try using httpd.handle_request ?

Upvotes: 0

Vincent Biragnet
Vincent Biragnet

Reputation: 2998

you can try :

from threading import Thread
...
t=Thread(target=start_server)
t.start()

(instead of start_server() directly)

Upvotes: 0

Related Questions