mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-04-07 06:07:32 +02:00
48 lines
1.7 KiB
Python
48 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
#
|
|
# Copyright (c) The Bitcoin Core developers
|
|
# Distributed under the MIT software license, see the accompanying
|
|
# file COPYING or https://opensource.org/license/mit/.
|
|
|
|
import time
|
|
import urllib.request
|
|
|
|
|
|
def download_from_url(url, archive):
|
|
last_print_time = time.time()
|
|
|
|
def progress_hook(progress_bytes, total_size):
|
|
nonlocal last_print_time
|
|
now = time.time()
|
|
percent = min(100, (progress_bytes * 100) / total_size)
|
|
bar_length = 40
|
|
filled_length = int(bar_length * percent / 100)
|
|
bar = '#' * filled_length + '-' * (bar_length - filled_length)
|
|
if now - last_print_time >= 1 or percent >= 100:
|
|
print(f'\rDownloading: [{bar}] {percent:.1f}%', flush=True, end="")
|
|
last_print_time = now
|
|
|
|
with urllib.request.urlopen(url) as response:
|
|
if response.status != 200:
|
|
raise RuntimeError(f"HTTP request failed with status code: {response.status}")
|
|
|
|
sock_info = response.fp.raw._sock.getpeername()
|
|
print(f"Connected to {sock_info[0]}")
|
|
|
|
total_size = int(response.getheader("Content-Length"))
|
|
progress_bytes = 0
|
|
|
|
with open(archive, 'wb') as file:
|
|
while True:
|
|
chunk = response.read(8192)
|
|
if not chunk:
|
|
break
|
|
file.write(chunk)
|
|
progress_bytes += len(chunk)
|
|
progress_hook(progress_bytes, total_size)
|
|
|
|
if progress_bytes < total_size:
|
|
raise RuntimeError(f"Download incomplete: expected {total_size} bytes, got {progress_bytes} bytes")
|
|
|
|
print('\n', flush=True, end="") # Flush to avoid error output on the same line.
|