how to show file size in MB in the 'wget' module?

Question:

I want to customize ‘bar_adaptive’ function from ‘wget’ module in python to show file size in MB instead of Byte, I mean output should be something like this:

45.0% [.........................                                ] 41.63 / 92.1 MB

instead of this:

 45% [.......................                               ] 43647584 / 96570345

in my current situation i’m using it like this:

# 'download_link' is downloading file url
# 'output' is path to download file
wget.download(url=download_link, out=output, bar=wget.bar_adaptive)

I will answer this question by myself.

Asked By: kamran mt21

||

Answers:

I used my own function as ‘bar’ argument in ‘download’ function that uses ‘bar_adaptive’ function under the hood:

# custom bar function:
# '/1024/1024' to convert Byte to MB
# 'round' is a python built-in function that rounds numbers. first argument is
#     number itself and second argument is The number of decimals to be considered
#     while rounding, default is 0. If 'round' function don't be used, result can
#     be something like: 41.625579834
# at end, I added ' MB' to be added in result.
def custom_bar(current, total, width=80):
    return wget.bar_adaptive(round(current/1024/1024, 2), round(total/1024/1024, 2), width) + ' MB'


# 'download_link' is downloading file url
# 'output' is path to download file
wget.download(url=download_link, out=output, bar=custom_bar)

alternatively, we can use a lambda function like this:

# 'download_link' is downloading file url
# 'output' is path to download file
wget.download(url=download_link, out=output, bar=lambda current, total, width=80: wget.bar_adaptive(round(current/1024/1024, 2), round(total/1024/1024, 2), width) + ' MB')

I hope it helps someone.

Answered By: kamran mt21
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.