假设我有一个像这样的异步函数:
async def foobar(argOne, argTwo, argThree):
print(argOne, argTwo, argThree)
Run Code Online (Sandbox Code Playgroud)
我想制作一个装饰器并在此函数上使用它,将上面的代码包装在 try except 语句中,如下所示:
try:
print(argOne, argTwo, argThree)
except:
print('Something went wrong.)
Run Code Online (Sandbox Code Playgroud)
有什么办法可以做到这一点吗?
S4e*_*3sm 11
因为首先调用包装器,所以我们还应该将其定义为异步函数:async def wrap(*arg, **kwargs):
import asyncio
def decorator(f):
async def wrapper(*arg, **kwargs):
try:
await f(*arg, **kwargs)
except Exception as e:
print('Something went wrong.', e)
return wrapper
@decorator
async def foobar(argOne, argTwo, argThree):
print(argOne, argTwo, argThree)
await asyncio.sleep(1)
asyncio.run(foobar("a", "b", "c"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4026 次 |
| 最近记录: |