Skip to content

Instantly share code, notes, and snippets.

@pohlt
Created November 2, 2021 04:16
Show Gist options
  • Save pohlt/49248c9285026e0834ed0ba44a90308f to your computer and use it in GitHub Desktop.
Save pohlt/49248c9285026e0834ed0ba44a90308f to your computer and use it in GitHub Desktop.
Basic download script
import argparse
import sys
# as seen in https://github.com/python/cpython/pull/29217
def download():
parser = argparse.ArgumentParser(
description="Download the provided URL (FTP/HTTP/HTTPS supported) "
"and print it to stdout by default. If specified, write to OUTPUT "
"instead."
)
parser.add_argument("URL", help="(encoded) URL to download")
parser.add_argument(
"-o",
"--output",
type=argparse.FileType('wb'), default=sys.stdout.buffer,
help="write to OUTPUT instead of stdout"
)
args = parser.parse_args()
buffer = memoryview(bytearray(32768))
try:
with urlopen(args.URL) as response:
while n_bytes_read := response.readinto(buffer):
args.output.write(buffer[:n_bytes_read])
except URLError as exc:
print(f"Error while downloading '{args.URL}': {exc.reason}")
if args.output is not sys.stdout.buffer:
args.output.close()
if __name__ == "__main__":
download()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment