How do I write output in same place on the console?
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
Downloading File FooFile.txt [47%]
Downloading File FooFile.txt [48%]
Downloading File FooFile.txt [49%]
How should I go about doing this?
Duplicate: How can I print over the current line in a command line application?
Solution 1:
You can also use the carriage return:
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
Solution 2:
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.')
Solution 3:
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.
Solution 4:
Print the backspace character \b
several times, and then overwrite the old number with the new number.