Kristian Kristian - 8 months ago 64
Python Question

output to the same line overwriting previous output ? python (2.5)

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!'

and output is something like this:

1784 KB / KB 1829 downloaded!
1788 KB / KB 1829 downloaded!

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?

Answer Source

Here's code for Python 3.x:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

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 the sys 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:

from __future__ import print_function