17db96d56Sopenharmony_ci# Simple Python script to download a file. Used as a fallback
27db96d56Sopenharmony_ci# when other more reliable methods fail.
37db96d56Sopenharmony_ci#
47db96d56Sopenharmony_cifrom __future__ import print_function
57db96d56Sopenharmony_ciimport sys
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_citry:
87db96d56Sopenharmony_ci    from requests import get
97db96d56Sopenharmony_ciexcept ImportError:
107db96d56Sopenharmony_ci    try:
117db96d56Sopenharmony_ci        from urllib.request import urlretrieve
127db96d56Sopenharmony_ci        USING = "urllib.request.urlretrieve"
137db96d56Sopenharmony_ci    except ImportError:
147db96d56Sopenharmony_ci        try:
157db96d56Sopenharmony_ci            from urllib import urlretrieve
167db96d56Sopenharmony_ci            USING = "urllib.retrieve"
177db96d56Sopenharmony_ci        except ImportError:
187db96d56Sopenharmony_ci            print("Python at", sys.executable, "is not suitable",
197db96d56Sopenharmony_ci                  "for downloading files.", file=sys.stderr)
207db96d56Sopenharmony_ci            sys.exit(2)
217db96d56Sopenharmony_cielse:
227db96d56Sopenharmony_ci    USING = "requests.get"
237db96d56Sopenharmony_ci
247db96d56Sopenharmony_ci    def urlretrieve(url, filename):
257db96d56Sopenharmony_ci        r = get(url, stream=True)
267db96d56Sopenharmony_ci        r.raise_for_status()
277db96d56Sopenharmony_ci        with open(filename, 'wb') as f:
287db96d56Sopenharmony_ci            for chunk in r.iter_content(chunk_size=1024):
297db96d56Sopenharmony_ci                f.write(chunk)
307db96d56Sopenharmony_ci        return filename
317db96d56Sopenharmony_ci
327db96d56Sopenharmony_ciif __name__ == '__main__':
337db96d56Sopenharmony_ci    if len(sys.argv) != 3:
347db96d56Sopenharmony_ci        print("Usage: urlretrieve.py [url] [filename]", file=sys.stderr)
357db96d56Sopenharmony_ci        sys.exit(1)
367db96d56Sopenharmony_ci    URL = sys.argv[1]
377db96d56Sopenharmony_ci    FILENAME = sys.argv[2]
387db96d56Sopenharmony_ci    print("Downloading from", URL, "to", FILENAME, "using", USING)
397db96d56Sopenharmony_ci    urlretrieve(URL, FILENAME)
40