Add theory for 6.14 section and done some naming changes
This commit is contained in:
parent
52d9cd53cb
commit
8b391c9845
15 changed files with 182 additions and 4 deletions
|
@ -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()
|
||||
|
|
|
@ -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}")
|
||||
|
|
33
6_tasks/6_14_050_exceptions.py
Normal file
33
6_tasks/6_14_050_exceptions.py
Normal file
|
@ -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())
|
35
6_tasks/6_14_051_exceptions.py
Normal file
35
6_tasks/6_14_051_exceptions.py
Normal file
|
@ -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())
|
33
6_tasks/6_14_052_exceptions.py
Normal file
33
6_tasks/6_14_052_exceptions.py
Normal file
|
@ -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 см в след файле
|
33
6_tasks/6_14_053_exceptions.py
Normal file
33
6_tasks/6_14_053_exceptions.py
Normal file
|
@ -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())
|
||||
|
35
6_tasks/6_14_054_exceptions.py
Normal file
35
6_tasks/6_14_054_exceptions.py
Normal file
|
@ -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())
|
|
@ -12,3 +12,7 @@ python = "^3.10"
|
|||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
|
||||
|
|
Loading…
Reference in a new issue