Created
May 14, 2024 10:14
-
-
Save leplatrem/be47a1f8115246e300f52b3b2c74b254 to your computer and use it in GitHub Desktop.
Resume download with requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import time | |
from urllib.parse import urlparse | |
import requests | |
def resume_download(url, filename): | |
resp = requests.head(url) | |
if "Accept-Ranges" not in resp.headers: | |
print("Resumable downloads not supported") | |
return | |
if os.path.exists(filename): | |
local_size = os.path.getsize(filename) | |
print(f"Resume previous download ({local_size}B)...") | |
else: | |
local_size = 0 | |
resp = requests.get(url, headers={"Range": f"bytes={local_size}-"}) | |
with open(filename, "ab") as f: | |
for chunk in resp.iter_content(chunk_size=1024): | |
if not chunk: | |
break | |
f.write(chunk) | |
print(".") | |
time.sleep(1) | |
if __name__ == "__main__": | |
url = sys.argv[1] | |
parsed = urlparse(url) | |
filename = os.path.basename(parsed.path) | |
resume_download(url, filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment