Steve Dower | 588836d | 2017-07-17 14:55:28 +0200 | [diff] [blame] | 1 | # Simple Python script to download a file. Used as a fallback |
| 2 | # when other more reliable methods fail. |
| 3 | # |
| 4 | from __future__ import print_function |
| 5 | import sys |
| 6 | |
| 7 | try: |
| 8 | from requests import get |
| 9 | except ImportError: |
| 10 | try: |
| 11 | from urllib.request import urlretrieve |
| 12 | USING = "urllib.request.urlretrieve" |
| 13 | except ImportError: |
| 14 | try: |
| 15 | from urllib import urlretrieve |
| 16 | USING = "urllib.retrieve" |
| 17 | except ImportError: |
| 18 | print("Python at", sys.executable, "is not suitable", |
| 19 | "for downloading files.", file=sys.stderr) |
| 20 | sys.exit(2) |
| 21 | else: |
| 22 | USING = "requests.get" |
| 23 | |
| 24 | def urlretrieve(url, filename): |
| 25 | r = get(url, stream=True) |
| 26 | r.raise_for_status() |
| 27 | with open(filename, 'wb') as f: |
| 28 | for chunk in r.iter_content(chunk_size=1024): |
| 29 | f.write(chunk) |
| 30 | return filename |
| 31 | |
| 32 | if __name__ == '__main__': |
| 33 | if len(sys.argv) != 3: |
| 34 | print("Usage: urlretrieve.py [url] [filename]", file=sys.stderr) |
| 35 | sys.exit(1) |
| 36 | URL = sys.argv[1] |
| 37 | FILENAME = sys.argv[2] |
| 38 | print("Downloading from", URL, "to", FILENAME, "using", USING) |
| 39 | urlretrieve(URL, FILENAME) |