The Python Oracle

How do I write output in same place on the console?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping

--

Chapters
00:00 Question
00:54 Accepted answer (Score 287)
01:08 Answer 2 (Score 62)
01:56 Answer 3 (Score 29)
02:15 Answer 4 (Score 16)
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/5171...

Question links:
[How can I print over the current line in a command line application?]: https://stackoverflow.com/questions/4653...

Answer 2 links:
[curses module]: http://docs.python.org/library/curses.ht...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #consoleoutput

#avk47



ACCEPTED ANSWER

Score 295


You can also use the carriage return:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()



ANSWER 2

Score 64


Python 2

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python 3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

PyCharm Debugger Console with Python 3

# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6

import time

print('Start.')
for i in range(100):
    time.sleep(0.02)
    print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')



ANSWER 3

Score 29


Use a terminal-handling library like the curses module:

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.




ANSWER 4

Score 16


Print the backspace character \b several times, and then overwrite the old number with the new number.