fix: keep temp image files until workbook save
This commit is contained in:
parent
0ce33a601f
commit
bfe3f168a2
@ -2,9 +2,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import re
|
||||
import ssl
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@ -251,7 +251,7 @@ def resize_image(image: XLImage, max_width: int, max_height: int) -> None:
|
||||
image.height = int(height * scale)
|
||||
|
||||
|
||||
def process_sheet(sheet, args: argparse.Namespace, ssl_context) -> list[RowResult]:
|
||||
def process_sheet(sheet, args: argparse.Namespace, ssl_context, temp_files: list[Path]) -> list[RowResult]:
|
||||
results: list[RowResult] = []
|
||||
|
||||
header_row = args.header_row
|
||||
@ -282,9 +282,12 @@ def process_sheet(sheet, args: argparse.Namespace, ssl_context) -> list[RowResul
|
||||
|
||||
try:
|
||||
payload, extension = download_image(url, args.timeout, ssl_context)
|
||||
image_buffer = io.BytesIO(payload)
|
||||
image_buffer.name = f"row_{row}{extension}"
|
||||
image = XLImage(image_buffer)
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=extension) as temp_file:
|
||||
temp_file.write(payload)
|
||||
temp_path = Path(temp_file.name)
|
||||
temp_files.append(temp_path)
|
||||
|
||||
image = XLImage(str(temp_path))
|
||||
resize_image(image, args.max_width, args.max_height)
|
||||
|
||||
anchor = f"{image_column_letter}{row}"
|
||||
@ -321,14 +324,19 @@ def main() -> int:
|
||||
|
||||
workbook = load_workbook(input_path)
|
||||
sheets = choose_sheets(workbook, args.sheet)
|
||||
temp_files: list[Path] = []
|
||||
|
||||
all_results: list[tuple[str, RowResult]] = []
|
||||
for sheet in sheets:
|
||||
sheet_results = process_sheet(sheet, args, ssl_context)
|
||||
sheet_results = process_sheet(sheet, args, ssl_context, temp_files)
|
||||
all_results.extend((sheet.title, item) for item in sheet_results)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
workbook.save(output_path)
|
||||
try:
|
||||
workbook.save(output_path)
|
||||
finally:
|
||||
for file_path in temp_files:
|
||||
file_path.unlink(missing_ok=True)
|
||||
|
||||
success_count = sum(1 for _, item in all_results if item.status == "ok")
|
||||
fail_count = sum(1 for _, item in all_results if item.status == "failed")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user