python output buffer problem

  The problem encountered, a piece of code, the print is in the front, the log is in the back, and the log in the log is in the front. That's the problem with the python output buffer.

  The python output buffer does not write to the file until it is full 4k, unless the cache is disabled or the output is forced or the program ends.

 

#!/usr/bin/python
#coding=utf-8
'''
Pause 1s output
'''

import time

def printStar(n):
        for i in range(n):
                print " * ",
                time.sleep(1)

if __name__ == '__main__':
        printStar( 10)

  One-time output after waiting for 10s:

  * * * * * * * * * *

#!/usr/bin/python
#coding=utf-8
'''
Pause 1s output
'''

import time
import sys


def printStar(n):
        for i in range(n):
                print " * ",
                sys.stdout.flush()
                time.sleep(1)

if __name__ == '__main__':
        printStar( 10)

  It is output one per second.

 

  The python program stdout will output to the buffer first, and then output when the buffer is full or the script ends, while stderr will not output to the buffer first. print will call the write method of sys.stdout.

  The solution:

  1. Add the -u parameter at runtime, such as # python -u test.py 

  2. Add the sys.stdout.flush() function after each print that is not to be buffered

  3. Add -u to the head of the script, for example #!/usr/local/bin/python -u, the reason is the same as method 1

  4. Add environment variables PYTHONUNBUFFERED=1

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325269473&siteId=291194637