In Python, why won't something print without a newline?

后端 未结 6 2354
轮回少年
轮回少年 2020-12-17 15:53
import time
import sys
sys.stdout.write(\"1\")
time.sleep(5)
print(\"2\")

will print \"12\" after 5 seconds

import time
import sys
         


        
6条回答
  •  心在旅途
    2020-12-17 16:04

    The sys.stdout.write command from the sys module purposefully prints out the statement without the \n character. This is how a normal call to the stdout stream works, such as in C++ or C, where the \n character must be added manually.

    However the print command provided by Python automatically adds a \n character to the string, therefore simplifying the code and making it easier to read.

    The reason the phenomenon in the first result happens is because the system is waiting for a flush to print out, which is provided by the \n character. You can avoid this by using this command, sys.stdout.flush(), which will flush the stdout stream which forces it to print.

提交回复
热议问题