How to write a download progress indicator in Python?
<p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>

<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>

<p>Here is what I came up with:</p>

<pre>
    sys.stdout.write(rem_file + "...")    
    urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)

    def dlProgress(count, blockSize, totalSize):
      percent = int(count*blockSize*100/totalSize)
      sys.stdout.write("%2d%%" % percent)
      sys.stdout.write("\b\b\b")
      sys.stdout.flush()
</pre>

<p>Output: MyFileName... 9%</p>

<p>Any other ideas or recommendations to do this? </p>

<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>

<p><strong>EDIT:</strong></p>

<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>

<pre>
    global rem_file # global variable to be used in dlProgress

    urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)

    def dlProgress(count, blockSize, totalSize):
      percent = int(count*blockSize*100/totalSize)
      sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
      sys.stdout.flush()
</pre>

<p>Output: MyFileName...9% </p>

<p>And the cursor shows up at the END of the line. Much better.</p>

<p>There's a text progress bar library for python at  <a href="http://pypi.python.org/pypi/progressbar/2.2">http://pypi.python.org/pypi/progressbar/2.2</a> that you might find useful: </p>

<blockquote>
  <p>This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.</p>
  
  <p>The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.</p>
  
  <p>The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.</p>
</blockquote>
