File size: 1,425 Bytes
28ad598 0021056 28ad598 0021056 28ad598 0021056 28ad598 0021056 28ad598 0021056 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import os
import tarfile
import zipfile
import gzip
import traceback
import requests
from os.path import join as p_join
from typing import Optional
from urllib3.connection import ConnectionError
def wget(url: str, cache_dir: str, filename: Optional[str] = None):
os.makedirs(cache_dir, exist_ok=True)
filename = os.path.basename(url) if not filename else filename
output_file = p_join(cache_dir, filename)
try:
with open(output_file, "wb") as f:
r = requests.get(url)
f.write(r.content)
except ConnectionError or KeyboardInterrupt:
traceback.print_exc()
os.remove(output_file)
return False
if output_file.endswith('.tar.gz') or output_file.endswith('.tgz') or output_file.endswith('.tar'):
if output_file.endswith('.tar'):
tar = tarfile.open(output_file)
else:
tar = tarfile.open(output_file, "r:gz")
tar.extractall(cache_dir)
tar.close()
os.remove(output_file)
elif output_file.endswith('.gz'):
with gzip.open(output_file, 'rb') as f:
with open(output_file.replace('.gz', ''), 'wb') as f_write:
f_write.write(f.read())
os.remove(output_file)
elif output_file.endswith('.zip'):
with zipfile.ZipFile(output_file, 'r') as zip_ref:
zip_ref.extractall(cache_dir)
os.remove(output_file)
return True
|