|
1 | | -from tempfile import TemporaryFile |
| 1 | +import os |
| 2 | +from tempfile import mkstemp |
2 | 3 | from typing import Optional |
3 | 4 |
|
4 | 5 | from .paratext_project_settings_parser_base import ParatextProjectSettingsParserBase |
|
7 | 8 |
|
8 | 9 | class ZipParatextProjectSettingsParserBase(ParatextProjectSettingsParserBase): |
9 | 10 | def _create_stylesheet(self, file_name: str) -> UsfmStylesheet: |
10 | | - with TemporaryFile() as stylesheet_temp_file, TemporaryFile() as custom_stylesheet_temp_file: |
| 11 | + stylesheet_temp_path: Optional[str] = None |
| 12 | + stylesheet_temp_fd: Optional[int] = None |
| 13 | + custom_stylesheet_temp_path: Optional[str] = None |
| 14 | + custom_stylesheet_temp_fd: Optional[int] = None |
| 15 | + try: |
11 | 16 | stylesheet_path: str = file_name |
12 | 17 | if self._exists(file_name): |
13 | | - with self._open(file_name) as source: |
| 18 | + stylesheet_temp_fd, stylesheet_temp_path = mkstemp() |
| 19 | + with ( |
| 20 | + self._open(file_name) as source, |
| 21 | + open(stylesheet_temp_fd, "wb", closefd=False) as stylesheet_temp_file, |
| 22 | + ): |
14 | 23 | stylesheet_temp_file.write(source.read()) |
15 | | - stylesheet_path = stylesheet_temp_file.name |
| 24 | + stylesheet_path = stylesheet_temp_path |
16 | 25 | custom_stylesheet_path: Optional[str] = None |
17 | 26 | if self._exists("custom.sty"): |
18 | | - with self._open("custom.sty") as source: |
| 27 | + custom_stylesheet_temp_fd, custom_stylesheet_temp_path = mkstemp() |
| 28 | + with ( |
| 29 | + self._open("custom.sty") as source, |
| 30 | + open(custom_stylesheet_temp_fd, "wb", closefd=False) as custom_stylesheet_temp_file, |
| 31 | + ): |
19 | 32 | custom_stylesheet_temp_file.write(source.read()) |
20 | | - custom_stylesheet_path = custom_stylesheet_temp_file.name |
| 33 | + custom_stylesheet_path = custom_stylesheet_temp_path |
21 | 34 | return UsfmStylesheet(stylesheet_path, custom_stylesheet_path) |
| 35 | + finally: |
| 36 | + if stylesheet_temp_fd is not None: |
| 37 | + os.close(stylesheet_temp_fd) |
| 38 | + if stylesheet_temp_path is not None: |
| 39 | + os.remove(stylesheet_temp_path) |
| 40 | + if custom_stylesheet_temp_fd is not None: |
| 41 | + os.close(custom_stylesheet_temp_fd) |
| 42 | + if custom_stylesheet_temp_path is not None: |
| 43 | + os.remove(custom_stylesheet_temp_path) |
0 commit comments