I'm trying to print two strings on the same line using a timer in between. Here's the code:
import time
print "hello",
time.sleep(2)
print "world"
But it seems the program waits for two seconds then prints both strings.
I'm trying to print two strings on the same line using a timer in between. Here's the code:
import time
print "hello",
time.sleep(2)
print "world"
But it seems the program waits for two seconds then prints both strings.
The issue is that , by default, the console output is buffered.
Since Python 3.3 print()
supports the keyword argument flush
(see documentation):
print('hello', flush=True)
If you use an prior versionf of python, you can force a flush like this:
import sys
sys.stdout.flush()
in python 2.7 you could use the print_function from the future package
from __future__ import print_function
from time import sleep
print("hello, ", end="")
sleep(2)
print("world!")
But like you said, this waits 2 seconds then prints both strings. In light of Gui Rava's answer you can flush stdout, here is a sample which should get you in the right direction:
import time
import sys
def _print(string):
sys.stdout.write(string)
sys.stdout.flush()
_print('hello ')
time.sleep(2)
_print('world')