| 1 |
""" |
| 2 |
A rudimentary URL downloader (like wget or curl) to demonstrate Rich progress bars. |
| 3 |
""" |
| 4 |
|
| 5 |
import os.path |
| 6 |
import sys |
| 7 |
from concurrent.futures import ThreadPoolExecutor |
| 8 |
import signal |
| 9 |
from functools import partial |
| 10 |
from threading import Event |
| 11 |
from typing import Iterable |
| 12 |
from urllib.request import urlopen |
| 13 |
|
| 14 |
from rich.progress import ( |
| 15 |
BarColumn, |
| 16 |
DownloadColumn, |
| 17 |
Progress, |
| 18 |
TaskID, |
| 19 |
TextColumn, |
| 20 |
TimeRemainingColumn, |
| 21 |
TransferSpeedColumn, |
| 22 |
) |
| 23 |
|
| 24 |
progress = Progress( |
| 25 |
TextColumn("[bold blue]{task.fields[filename]}", justify="right"), |
| 26 |
BarColumn(bar_width=None), |
| 27 |
"[progress.percentage]{task.percentage:>3.1f}%", |
| 28 |
"•", |
| 29 |
DownloadColumn(), |
| 30 |
"•", |
| 31 |
TransferSpeedColumn(), |
| 32 |
"•", |
| 33 |
TimeRemainingColumn(), |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
done_event = Event() |
| 38 |
|
| 39 |
|
| 40 |
def handle_sigint(signum, frame): |
| 41 |
done_event.set() |
| 42 |
|
| 43 |
|
| 44 |
signal.signal(signal.SIGINT, handle_sigint) |
| 45 |
|
| 46 |
|
| 47 |
def copy_url(task_id: TaskID, url: str, path: str) -> None: |
| 48 |
"""Copy data from a url to a local file.""" |
| 49 |
progress.console.log(f"Requesting {url}") |
| 50 |
response = urlopen(url) |
| 51 |
# This will break if the response doesn't contain content length |
| 52 |
progress.update(task_id, total=int(response.info()["Content-length"])) |
| 53 |
with open(path, "wb") as dest_file: |
| 54 |
progress.start_task(task_id) |
| 55 |
for data in iter(partial(response.read, 32768), b""): |
| 56 |
dest_file.write(data) |
| 57 |
progress.update(task_id, advance=len(data)) |
| 58 |
if done_event.is_set(): |
| 59 |
return |
| 60 |
progress.console.log(f"Downloaded {path}") |
| 61 |
|
| 62 |
|
| 63 |
def download(urls: Iterable[str], dest_dir: str): |
| 64 |
"""Download multiple files to the given directory.""" |
| 65 |
|
| 66 |
with progress: |
| 67 |
with ThreadPoolExecutor(max_workers=4) as pool: |
| 68 |
for url in urls: |
| 69 |
filename = url.split("/")[-1] |
| 70 |
dest_path = os.path.join(dest_dir, filename) |
| 71 |
task_id = progress.add_task("download", filename=filename, start=False) |
| 72 |
pool.submit(copy_url, task_id, url, dest_path) |
| 73 |
|
| 74 |
|
| 75 |
if __name__ == "__main__": |
| 76 |
# Try with https://releases.ubuntu.com/noble/ubuntu-24.04-desktop-amd64.iso |
| 77 |
# and https://releases.ubuntu.com/noble/ubuntu-24.04-live-server-amd64.iso |
| 78 |
if sys.argv[1:]: |
| 79 |
download(sys.argv[1:], "./") |
| 80 |
else: |
| 81 |
print("Usage:\n\tpython downloader.py URL1 URL2 URL3 (etc)") |