NiltonVolpato / python-progressbar

Text progress bar library for Python
Other
412 stars 105 forks source link

Handle UnknownLength everywhere. #48

Closed kousu closed 6 years ago

kousu commented 8 years ago

I have this code (on top of python-requests):

c = 0
try:
       M = int(export.headers['content-length'])
except KeyError:
      M = progressbar.UnknownLength

bar = progressbar.ProgressBar(maxval=M,
           widgets=[progressbar.FileTransferSpeed(), ' ', 
           progressbar.Bar('=', '[', ']'), ' ',
           progressbar.Percentage()]).start()
with open(filename(export.url),"wb") as o:
    for block in export.iter_content():
        o.write(block)
        c+=len(block)
        bar.update(c)
bar.finish()

I want it to show me a percentage ticker if it can, but to gracefully fall back if the remote server doesn't send a Content-Length. But instead I get:

  File "/usr/lib/python3.5/site-packages/progressbar/__init__.py", line 208, in percentage
    return self.currval * 100.0 / self.maxval

This patches this problem. I don't know if it's totally correct, but I would like to raise the issue.

kousu commented 8 years ago

And when doing this I came across progressbar.widgets.Bar.update which says:

        if pbar.maxval:
          marked *= int(pbar.currval / pbar.maxval * width)

which suggests to me that instead of UnknownLength it might be simpler just to declare maxval==None to mean the length is unknown (since 'if UnknownLength' passes the check and goes into the branch).

kousu commented 8 years ago

Or maybe the thing to do is to use float("NaN" as the "unknown" value, so that the calculations can be left in place, but detect it in the views and display it as blank space or "N/A" or whatever is appropriate.

kousu commented 7 years ago

Is there any interest in this or should I close the PR?

NiltonVolpato commented 6 years ago

Sorry for the delay. I think I need to add some automated tests, verifying by hand is time consuming. I probably didn't have time to do right when you sent the pull request, then I ended up forgetting about it.