Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
35 lines
997 B
Python
35 lines
997 B
Python
"""
|
|
Модуль context_managers.py содержит контекстные менеджеры для управления ресурсами.
|
|
"""
|
|
|
|
import os
|
|
import contextlib
|
|
from typing import Generator, BinaryIO
|
|
import logging
|
|
|
|
logger = logging.getLogger('app.context_managers')
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def open_file(file_path: str, mode: str = 'rb') -> Generator[BinaryIO, None, None]:
|
|
"""
|
|
Контекстный менеджер для безопасного открытия и закрытия файлов.
|
|
|
|
Args:
|
|
file_path: Путь к файлу.
|
|
mode: Режим открытия файла.
|
|
|
|
Yields:
|
|
Файловый объект.
|
|
"""
|
|
file_obj = None
|
|
try:
|
|
file_obj = open(file_path, mode)
|
|
yield file_obj
|
|
except Exception as e:
|
|
logger.error(f"Ошибка при работе с файлом {file_path}: {e}")
|
|
raise
|
|
finally:
|
|
if file_obj:
|
|
file_obj.close()
|