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

后端 未结 6 2330
轮回少年
轮回少年 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:03

    If you add "\n" then stream is flushed automaticaly, and it is not without new line at the end. You can flush output with:

    sys.stdout.flush()

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 16:14

    Consider that when you type a command into a computer, it doesn't know you're finished until you press ENTER

    Similarly, the newline tells Python you've finished that line.

    0 讨论(0)
  • 2020-12-17 16:16

    It's because output in Python is buffered by default - ordinarily you won't get the output until the buffer is full or something causes the buffer to be flushed. In this case the \n was sensed and caused an automatic flush.

    See this question for ways around the problem: How to flush output of Python print?

    0 讨论(0)
  • 2020-12-17 16:17

    Buffering. It's not really Python, but rather your operating system/terminal. Output from any program is sent to a buffer, a holding area of memory. When a whole line is collected, it's sent to the screen. There is usually a hook, a method named something like flush(), to force output of partial lines.

    0 讨论(0)
  • 2020-12-17 16:23

    Because stdout is buffered. You may be able to force the output sooner with a sys.stdout.flush() call.

    0 讨论(0)
提交回复
热议问题