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.
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.
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).
Your code works in my computer. You can try to flush the stdout directly after printing hello
import sys
sys.stdout.flush()
确保您已从 python 导入时间库,并在两个版本的 python 上尝试,看看是否会遇到相同的错误。我已经尝试过了,它有效。