Problems with Python output buffers

Source: Internet
Author: User

Encountered the problem, a piece of code, print in front, log in the post, look at the log in the logs instead of the front. is a problem with the Python output buffer.

The python output buffer is up to 4k before writing to the file unless the cache is disabled or the output is forced or the program ends. Intermediate CTRL + C interrupts will lose some output.

#!/usr/bin/python#Coding=utf-8" "pause 1s output" "Import TimedefPrintstar (n): forIinchrange (n):Print " * ", Time.sleep (1)if __name__=='__main__': Printstar (10)

Wait for 10s output once:

* * * * * * * * * *

#!/usr/bin/python#Coding=utf-8" "pause 1s output" "Import TimeImportSYSdefPrintstar (n): forIinchrange (n):Print " * ", Sys.stdout.flush () Time.sleep (1)if __name__=='__main__': Printstar (10)

The output is one second.

The Python program stdout output to a buffer, wait until the buffer is full or the script ends and then output, and the stderr does not output to the buffer first. Print calls Sys.stdout's Write method.

The solution:

1, run-time plus-u parameters, such as# python -u test.py 

2. Add the Sys.stdout.flush () function after each print that does not buffer

3. Add Environment variablesPYTHONUNBUFFERED=1

Problems with Python output buffers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.