diff --git a/src/calibre/devices/mtp/driver.py b/src/calibre/devices/mtp/driver.py index 7837cd1de3..9162572ffe 100644 --- a/src/calibre/devices/mtp/driver.py +++ b/src/calibre/devices/mtp/driver.py @@ -644,19 +644,19 @@ class MTP_DEVICE(BASE): def upload_apnx(self, parent, filename, storage, mi, filepath): from calibre.devices.kindle.apnx import APNXBuilder - import tempfile + from calibre.ptempfile import PersistentTemporaryFile - apnx_local_path = tempfile.NamedTemporaryFile(prefix='calibre-apnx-', suffix='.apnx', delete=False).name + apnx_local_file = PersistentTemporaryFile('.apnx') + apnx_local_path = apnx_local_file.name + apnx_local_file.close() try: - apnx_builder = APNXBuilder() - custom_page_count = 0 cust_col_name = self.get_pref('apnx').get('custom_column_page_count', None) if cust_col_name: try: custom_page_count = int(mi.get(cust_col_name, 0)) - except: + except Exception: pass method = self.get_pref('apnx').get('method', 'fast') @@ -668,23 +668,22 @@ class MTP_DEVICE(BASE): method = method.lower() if method not in ('fast', 'accurate', 'pagebreak'): method = None - except: + except Exception: prints(f'Invalid custom column method: {cust_col_method}, ignoring') + apnx_builder = APNXBuilder() apnx_builder.write_apnx(filepath, apnx_local_path, method=method, page_count=custom_page_count) apnx_size = os.path.getsize(apnx_local_path) - apnx_stream = open(apnx_local_path, 'rb') - try: + with open(apnx_local_path, 'rb') as apnx_stream: name = filename.rpartition('.')[0] apnx_filename = f'{name[:-2]}.apnx' apnx_path = parent.name, f'{name[:-2]}.sdr', apnx_filename sdr_parent = self.ensure_parent(storage, apnx_path) self.put_file(sdr_parent, apnx_filename, apnx_stream, apnx_size) - finally: - apnx_stream.close() - except: + + except Exception: print('Failed to generate APNX') import traceback traceback.print_exc()