Monday, March 28, 2011

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: http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360

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

    Chris Ballance : interesting, I hadn't thought of doing it that way.
  • 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.

  • You can also use the carriage return:

    sys.stdout.write("Download progress: %d%%   \r" % (progress) )
    
    ephemient : Very common and simple solution. Note: if your line is longer than the width of your terminal, this gets ugly.
    scottm : I also had to add a call to sys.stdout.flush() so the cursor didn't bounce around
  • 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,
    

0 comments:

Post a Comment