diff --git a/4_polling/polling.py b/4_polling/polling.py index d6ab9d3..7f64472 100644 --- a/4_polling/polling.py +++ b/4_polling/polling.py @@ -9,8 +9,8 @@ async def print_message(): async def interrupt_handler(interrupt_flag): while True: - # Ждем установки флага. - await interrupt_flag.wait() + # Ждем установки флага. + await interrupt_flag.wait() print("Произошло прерывание! В этом месте может быть установлен любой обработчик") # Очищаем флаг для следующего использования interrupt_flag.clear() diff --git a/6_tasks/6_3_4_task.py b/6_tasks/6_03_4_task.py similarity index 100% rename from 6_tasks/6_3_4_task.py rename to 6_tasks/6_03_4_task.py diff --git a/6_tasks/6_4_01_weather.py b/6_tasks/6_04_01_weather.py similarity index 100% rename from 6_tasks/6_4_01_weather.py rename to 6_tasks/6_04_01_weather.py diff --git a/6_tasks/6_5_03_task.py b/6_tasks/6_05_03_task.py similarity index 100% rename from 6_tasks/6_5_03_task.py rename to 6_tasks/6_05_03_task.py diff --git a/6_tasks/6_5_10_reports.py b/6_tasks/6_05_10_reports.py similarity index 100% rename from 6_tasks/6_5_10_reports.py rename to 6_tasks/6_05_10_reports.py diff --git a/6_tasks/6_7_04_warehouse.py b/6_tasks/6_07_04_warehouse.py similarity index 100% rename from 6_tasks/6_7_04_warehouse.py rename to 6_tasks/6_07_04_warehouse.py diff --git a/6_tasks/6_9_07_rings.py b/6_tasks/6_09_07_rings.py similarity index 100% rename from 6_tasks/6_9_07_rings.py rename to 6_tasks/6_09_07_rings.py diff --git a/6_tasks/6_9_cancelation.py b/6_tasks/6_09_cancelation.py similarity index 100% rename from 6_tasks/6_9_cancelation.py rename to 6_tasks/6_09_cancelation.py diff --git a/6_tasks/6_12_07_callbacks.py b/6_tasks/6_12_07_callbacks.py index 69eef4e..d2e01c8 100644 --- a/6_tasks/6_12_07_callbacks.py +++ b/6_tasks/6_12_07_callbacks.py @@ -37,12 +37,17 @@ messages = [ ] -async def print_message(message): +async def print_message( + message, +): # print(f"Сообщение: {message}") return message -def print_code(task: asyncio.Task): +def print_code( + task: asyncio.Task, +): + task.items() message_code = codes.pop(0) task_message = task.result() print(f"Сообщение: {task_message}\nКод: {message_code}") diff --git a/6_tasks/6_14_050_exceptions.py b/6_tasks/6_14_050_exceptions.py new file mode 100644 index 0000000..e69a70c --- /dev/null +++ b/6_tasks/6_14_050_exceptions.py @@ -0,0 +1,33 @@ +import asyncio + + +async def coro(): + name = asyncio.current_task().get_name() + print(f'{name} начала свою работу!') + await asyncio.sleep(1) + print(f'{name} завершена!') + + +# Корутина для подъема исключений +async def ex_coro(): + await asyncio.sleep(.5) +# 1) Поведение характерное для обработки KeyboardInterrupt и SystemExit +# Повторный вызов изначального исключения + # print('ex_coro поднимает исключение KeyboardInterrupt') + # raise KeyboardInterrupt +# 2) Поведение характерное для обработки других исключений (кроме asyncio.CancelledError) +# Исключения группируются в ExceptionGroup + print('ex_coro поднимает исключение Exсeption') + raise Exception('Что-то пошло не так!(((') + + +async def main(): + # Создание группы задач + async with asyncio.TaskGroup() as group: + # Создание трех задач + tasks = [group.create_task(coro(), name=f'Задача_0{i}') for i in range(1, 4)] + # Создание задачи, имитирующей возникновение исключения + task_ex = group.create_task(ex_coro()) + + +asyncio.run(main()) diff --git a/6_tasks/6_14_051_exceptions.py b/6_tasks/6_14_051_exceptions.py new file mode 100644 index 0000000..08781ae --- /dev/null +++ b/6_tasks/6_14_051_exceptions.py @@ -0,0 +1,35 @@ +import asyncio + + +async def coro(): + name = asyncio.current_task().get_name() + print(f'{name} начала свою работу!') + await asyncio.sleep(1) + print(f'{name} завершена!') + + +async def ex_coro(): + await asyncio.sleep(.5) + # Вызываем исключение + print('ex_coro поднимает исключение Exсeption') + raise Exception('Что-то пошло не так!(((') + + +async def main(): + try: + # Создание группы задач + async with asyncio.TaskGroup() as group: + # Создание трех задач + tasks = [group.create_task(coro(), name=f'Задача_0{i}') for i in range(1, 4)] + # Создание задачи, имитирующей возникновение исключения + tasks.append(group.create_task(ex_coro(), name='Задача_ex')) + except: + pass + + # Проверка состояния каждой задачи + for task in tasks: + print(f'{task.get_name()}: done={task.done()}, cancelled={task.cancelled()}') + print(f'{task.get_name()}: {tasks[-1].exception()}') + + +asyncio.run(main()) diff --git a/6_tasks/6_14_052_exceptions.py b/6_tasks/6_14_052_exceptions.py new file mode 100644 index 0000000..ee13cc7 --- /dev/null +++ b/6_tasks/6_14_052_exceptions.py @@ -0,0 +1,33 @@ +import asyncio + + +async def file_reader(filename: str) -> str: + """Корутина для чтения файла""" + with open(filename) as f: + data: str = f.read() + return data + + +async def get_data(data: int) -> dict: + """Корутина, для возврата переданного числа в виде словаря вида {'data': data}""" + if data == 0: + raise Exception("Нет данных...") + return {"data": data} + + +async def main(): + tasks = asyncio.gather( + get_data(1), + get_data(2), + # Передаем имя несуществующего файла, чтобы вызвать ошибку + file_reader("fake.png"), + # Этот вызов тоже должен вызвать ошибку + get_data(0), + ) + result = await tasks + print("Готово!!!", result) + + +asyncio.run(main()) + +# Решение через raise_excpetion см в след файле diff --git a/6_tasks/6_14_053_exceptions.py b/6_tasks/6_14_053_exceptions.py new file mode 100644 index 0000000..e2de1e2 --- /dev/null +++ b/6_tasks/6_14_053_exceptions.py @@ -0,0 +1,33 @@ +import asyncio + + +async def file_reader(filename: str) -> str: + """Корутина для чтения файла""" + with open(filename) as f: + data: str = f.read() + return data + + +async def get_data(data: int) -> dict: + """Корутина, для возврата переданного числа в виде словаря вида {'data': data}""" + if data == 0: + raise Exception("Нет данных...") + return {"data": data} + + +async def main(): + tasks = asyncio.gather( + get_data(1), + get_data(2), + # Передаем имя несуществующего файла, чтобы вызвать ошибку + file_reader("fake.png"), + # Этот вызов тоже должен вызвать ошибку + get_data(0), + return_exceptions=True + ) + result = await tasks + print("Готово!!!", result) + + +asyncio.run(main()) + diff --git a/6_tasks/6_14_054_exceptions.py b/6_tasks/6_14_054_exceptions.py new file mode 100644 index 0000000..4db6663 --- /dev/null +++ b/6_tasks/6_14_054_exceptions.py @@ -0,0 +1,35 @@ +import asyncio + + +async def file_reader(filename: str) -> str: + """Корутина для чтения файла""" + with open(filename) as f: + data: str = f.read() + return data + + +async def get_data(data: int) -> dict: + """Корутина, для возврата переданного числа в виде словаря вида {'data': data}""" + if data == 0: + raise Exception("Нет данных...") + return {"data": data} + + +async def main(): + try: + async with asyncio.TaskGroup() as tg: + task1 = tg.create_task(get_data(1)) + task2 = tg.create_task(get_data(2)) + task3 = tg.create_task(file_reader("fake.png")) + task4 = tg.create_task(get_data(0)) + result = [task1.result(), task2.result(), task3.result(), task4.result()] + print("Готово!!!", result) + except* FileNotFoundError as err: + for error in err.exceptions: + print(error) + except* Exception as err: + for error in err.exceptions: + print(error) + + +asyncio.run(main()) diff --git a/pyproject.toml b/pyproject.toml index ee41bb2..13cd5f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,3 +12,7 @@ python = "^3.10" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" + +[tool.ruff] +line-length = 120 +