Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

支持在事件循环已经运行时同步执行异步代码 #743

Merged
merged 3 commits into from
Apr 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()