4

In my python code having:

print "Hello"
time.sleep(20)
print "world"

I am expecting output as

Hello 

and then after 20 seconds

world

But Hello and world are printing simultaneously in the console.

4

3 回答 3

5

print operator effectively uses sys.stdout stream for output which is buffered. For real-time output you'll want to use sys.stderr stream which is not buffered:

import sys, time
sys.stderr.write("Hello ")
time.sleep(20)
sys.stderr.write("world\n")

Alternatively, you can flush stream buffer manually by calling sys.stdout.flush() each time you want to get output but I suggest you not to do it in such way unless you know what you're doing.

For more details there is an article in Wikipedia on standard streams (stdin, stdout and stderr).

于 2013-05-13T12:08:52.880 回答
1

Your code works in my computer. You can try to flush the stdout directly after printing hello

import sys
sys.stdout.flush()
于 2013-05-13T12:08:49.393 回答
-1

确保您已从 python 导入时间库,并在两个版本的 python 上尝试,看看是否会遇到相同的错误。我已经尝试过了,它有效。

于 2019-08-30T18:26:19.667 回答