I am writing a simple ftp downloader. Part of to the code is something like this:
ftp.retrbinary("RETR " + file_name, process)
i am calling function process to handle the callback:
def process(data):
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
file.write(data)
and output is something like this:
1784 KB / KB 1829 downloaded!
1788 KB / KB 1829 downloaded!
etc...
but i want it to print this line and next time reprint/refresh it so it will only show it once and i will see progress of that download...
How can it be done?
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
I found that for a simple print statement in python 2.7, just put a comma at the end after your
'\r'
.This is shorter than other non-python 3 solutions, but also more difficult to maintain.
Here's code for Python 3.x:
The
end=
keyword is what does the work here -- by default,print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import thesys
module for this sort of simple usage.print()
actually has a number of keyword arguments which can be used to greatly simplify code.To use the same code on Python 2.6+, put the following line at the top of the file:
I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - https://github.com/spyder-ide/spyder/issues/3437
Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.
If all you want to do is change a single line, use
\r
.\r
means carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly,\b
can be used to go one character backward. (some terminals may not support all those features)