This commit is contained in:
yumoqing 2025-08-08 12:33:17 +08:00
parent b0938027f4
commit c05d9a87b8

View File

@ -2,6 +2,7 @@ import time
import random import random
import asyncio import asyncio
import inspect import inspect
import concurrent
from functools import wraps from functools import wraps
from functools import wraps from functools import wraps
@ -9,15 +10,15 @@ def awaitify(sync_func):
"""Wrap a synchronous callable to allow ``await``'ing it""" """Wrap a synchronous callable to allow ``await``'ing it"""
@wraps(sync_func) @wraps(sync_func)
async def async_func(*args, **kw): async def async_func(*args, **kw):
loop = asyncio.get_event_loop() loop = None
return await loop.run_in_executor(None, sync_func, *args, **kw) try:
return async_func loop = asyncio.get_event_loop()
except:
def coroutinify(func): loop = asyncio.new_event_loop()
@wraps(func) # Run the blocking generation in a background thread
async def async_func(*args): with concurrent.futures.ThreadPoolExecutor() as pool:
loop = asyncio.get_event_loop() return await loop.run_in_executor(pool,
return await loop.run_in_executor(None, func, *args) lambda:sync_func(*args, **kw))
return async_func return async_func
def to_func(func): def to_func(func):