I have the below
foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
print choice(foo)
The output is:
a
c
a
e
...
I want the terminal output to overwrite the old output on the same line
thanks
I have the below
foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
print choice(foo)
The output is:
a
c
a
e
...
I want the terminal output to overwrite the old output on the same line
thanks
you can remove the old output by
import sys
sys.stdout.write( '\b' ) # removes the last outputed character
and you possibly need to use flush
after each print
sys.stdout.flush()
something like this:
from __future__ import print_function
import time
for j in range( 10 ):
print( j, end='' )
sys.stdout.flush()
time.sleep( 2 )
sys.stdout.write( '\b' )
You have two things to override: one, python will automatically add a newline when you print
. Override that by adding a comma at the end, like @SteveP says (or said at least :-)).
Next, you need to explicitly add a carriage return control character to the front of your string so that the terminal output will overwrite your previous output, as opposed to appending it to the end.
foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
print '\r' + choice(foo),
(might want a time.sleep
in there so you can actually see what's happening)