简体   繁体   中英

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?

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

you can try :

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

(instead of start_server() directly)

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM