pythonpython-3.xsimplehttpserver

Print statements not working when serve_forever() is called?


I have the following small python script to run a local server for testing some html:

print('opened')

from http.server import HTTPServer, SimpleHTTPRequestHandler

server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

print("Listening at https://127.0.0.1:8000/ . . .")
httpd.serve_forever()

When I run this in the terminal, it blocks the print statements: nothing is printed. But the server works and I can go to localhost:8000 in the browser and access my html files. If, however, I comment out the last line, the call to serve_forever(), it works, printing both opened and Listening at https:127.0.0.1:8000/ . . .. Except of course it doesn't actually work, since now the server isn't being run.

I find this very confusing. The previous lines are executed before the last line. Why would the last line cause the previous lines to not work?

Python3 on Windows7 if anyone was going to ask, but I doubt that's relevant.


Solution

  • That maybe related with the "infamous" need to flush in order for your prints to work!

    Related reading material:


    Because you are using Python 3 and since version 3.3 you don't have to follow the solutions given in the above great answers.
    The print build-in type has an option flush which by default is False. Do:

    print('opened', flush=True)
    
    from http.server import HTTPServer, SimpleHTTPRequestHandler
    
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    
    print('Listening at https://127.0.0.1:8000/ . . .', flush=True)
    httpd.serve_forever()
    

    PS: This is a confirmed solution on a similar issue