Skip to content

Commit

Permalink
Merge pull request #743 from LondonClass/patch-1
Browse files Browse the repository at this point in the history
支持在事件循环已经运行时同步执行异步代码
  • Loading branch information
z0z0r4 authored Apr 13, 2024
2 parents ef4d346 + d0a3870 commit 6a2ac4a
Showing 1 changed file with 12 additions and 18 deletions.
30 changes: 12 additions & 18 deletions bilibili_api/utils/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,23 @@
"""

import asyncio
from typing import Any, TypeVar, Coroutine
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Coroutine

T = TypeVar("T")


def __ensure_event_loop() -> None:
try:
asyncio.get_event_loop()

except:
asyncio.set_event_loop(asyncio.new_event_loop())


def sync(coroutine: Coroutine[Any, Any, T]) -> T:
def sync(coroutine: Coroutine) -> Any:
"""
同步执行异步函数,使用可参考 [同步执行异步代码](https://nemo2011.github.io/bilibili-api/#/sync-executor)
Args:
coroutine (Coroutine): 异步函数
coroutine (Coroutine): 执行异步函数所创建的协程对象
Returns:
该异步函数的返回值
该协程对象的返回值
"""
__ensure_event_loop()
loop = asyncio.get_event_loop()
return loop.run_until_complete(coroutine)
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coroutine)
else:
with ThreadPoolExecutor() as executor:
return executor.submit(asyncio.run, coroutine).result()

0 comments on commit 6a2ac4a

Please sign in to comment.