I'm going to make a telegram downloader bot using python-telegram-bot. at this point, I need a solution to download files with the requests library and pass its real-time percentage to python-telegram-bot. After googling I found out all solutions using tqdm, in my case, it's not possible to use it. So I Found this:
import time
import requests
import sys
# use a context manager to make an HTTP request and file
with requests.get("http://speedtest-sgp1.digitalocean.com/5gb.test", stream=True) as r:
with open('download.txt', 'wb') as file:
# Get the total size, in bytes, from the response header
total_size = int(r.headers.get('Content-Length'))
# Define the size of the chunk to iterate over (Mb)
chunk_size = 100000000
# iterate over every chunk and calculate % of total
for i, chunk in enumerate(r.iter_content(chunk_size=chunk_size)):
# calculate current percentage
c = i * chunk_size / total_size * 100
# write current % to console, pause for .1ms, then flush console
sys.stdout.write(f"\r{round(c, 4)}%")
time.sleep(.1)
sys.stdout.flush()
It works but slightly reduces download speed and uses a high amount of system resources. I think it's not a good way to do this. So I need a way to do this without tqdm and in an optimized way. Please tell me if you mind any other libraries that seem better than requests. Thanks!