aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorCody Logan <cody@lokken.dev>2023-11-08 09:42:51 -0800
committerCody Logan <cody@lokken.dev>2023-11-08 09:42:51 -0800
commit456316f882834c33e90a2ddfa8d4c5e47966dc5e (patch)
tree1c850bd0a5d6ef369995fe19128b07b90e04608b /src
parent26019422d956a85f1a210e67e6842acd4e4bc3f9 (diff)
downloadwikiget-456316f882834c33e90a2ddfa8d4c5e47966dc5e.tar.gz
wikiget-456316f882834c33e90a2ddfa8d4c5e47966dc5e.zip
Ensure downloaded file handler is always closed
Diffstat (limited to 'src')
-rw-r--r--src/wikiget/dl.py34
1 files changed, 16 insertions, 18 deletions
diff --git a/src/wikiget/dl.py b/src/wikiget/dl.py
index deb82a4..980ce1d 100644
--- a/src/wikiget/dl.py
+++ b/src/wikiget/dl.py
@@ -149,30 +149,28 @@ def download(f: File, args: Namespace) -> int:
if args.dry_run:
adapter.warning("Dry run; download skipped")
- return 0
+ return errors
try:
- fd = open(dest, "wb")
+ with tqdm(
+ desc=dest,
+ leave=args.verbose >= wikiget.STD_VERBOSE,
+ total=file_size,
+ unit="B",
+ unit_scale=True,
+ unit_divisor=wikiget.CHUNKSIZE,
+ ) as progress_bar, open(dest, "wb") as fd:
+ # download the file using the existing Site session
+ res = site.connection.get(file_url, stream=True)
+ for chunk in res.iter_content(wikiget.CHUNKSIZE):
+ fd.write(chunk)
+ progress_bar.update(len(chunk))
except OSError as e:
adapter.error(f"File could not be written: {e}")
errors += 1
return errors
- # download the file(s)
- leave_bars = args.verbose >= wikiget.STD_VERBOSE
- with tqdm(
- desc=dest,
- leave=leave_bars,
- total=file_size,
- unit="B",
- unit_scale=True,
- unit_divisor=wikiget.CHUNKSIZE,
- ) as progress_bar, fd:
- res = site.connection.get(file_url, stream=True)
- for chunk in res.iter_content(wikiget.CHUNKSIZE):
- fd.write(chunk)
- progress_bar.update(len(chunk))
-
- # verify file integrity and log details
+
+ # verify file integrity and log the details
try:
dl_sha1 = verify_hash(dest)
except OSError as e: