Print statements not working when serve_forever() is called?

后端 未结 3 581
半阙折子戏
半阙折子戏 2021-01-03 04:12

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

print(\'opened\')

from http.server import HTTPServer, SimpleHTTPReques         


        
3条回答
  •  天涯浪人
    2021-01-03 04:38

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

    Related reading material:

    • Theoretical knowledge on the subject
    • How to flush output of Python print?, python `print` does not work in loop, as suggested by @Kerorin:


    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

提交回复
热议问题