Print statements not working when serve_forever() is called?

后端 未结 3 532
半阙折子戏
半阙折子戏 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:36

    There several solutions for this phenomena:

    Disable output buffering

    Reopen stdout file descriptor with write mode, and 0 as the buffer size (unbuffered). I suggest to write this line as the first line in your code, and this way, all your code will remain the same except the stdout buffer:

    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    

    Run python with unbuffered binary stdout and stderr

    Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file.

    So just run your script like this:

    python -u 
    

    Or by setting the environment variable PYTHONUNBUFFERED

    Set flush keyword argument to true

    Since Python 3.3, you can force the normal print() function to flush without the need to use sys.stdout.flush() just set the "flush" keyword argument to true:

    print("...", flush=True)
    

    Changing the default in one module to flush=True

    You can change the default for the print function by using functools.partial on the global scope of a module:

    import functools
    print = functools.partial(print, flush=True)
    

    We can see it works just as expected:

    >>> print('foo')
    foo
    

提交回复
热议问题