import os from os.path import join as p_join from typing import Optional import tarfile import zipfile import gzip import requests __all__ = 'wget' def wget(url: str, cache_dir: str, filename: Optional[str] = None, uncompress_file: bool = True): os.makedirs(cache_dir, exist_ok=True) filename = os.path.basename(url) if not filename else filename output_file = p_join(cache_dir, filename) with open(output_file, "wb") as f: r = requests.get(url) f.write(r.content) if not uncompress_file: return output_file 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) return output_file.replace('.tar.gz', '').replace('.tgz', '').replace('.tar', '') 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) return output_file.replace('.gz', '') elif output_file.endswith('.zip'): with zipfile.ZipFile(output_file, 'r') as zip_ref: zip_ref.extractall(cache_dir) os.remove(output_file) return output_file.replace('.zip', '') return output_file if __name__ == '__main__': wget()