From 103f506c9491321f6e54d6cde64706cf3e18ccdf Mon Sep 17 00:00:00 2001 From: LondonClass <43668206+LondonClass@users.noreply.github.com> Date: Sat, 13 Apr 2024 02:20:42 +0800 Subject: [PATCH 1/3] Update sync.py --- bilibili_api/utils/sync.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/bilibili_api/utils/sync.py b/bilibili_api/utils/sync.py index 03622213..d44fdfb9 100644 --- a/bilibili_api/utils/sync.py +++ b/bilibili_api/utils/sync.py @@ -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(lambda: asyncio.run(coroutine)).result() From b700523d6d5ba2952899a5bd1e128a3d7cfbfc13 Mon Sep 17 00:00:00 2001 From: LondonClass <43668206+LondonClass@users.noreply.github.com> Date: Sat, 13 Apr 2024 02:38:46 +0800 Subject: [PATCH 2/3] Update sync.py --- bilibili_api/utils/sync.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bilibili_api/utils/sync.py b/bilibili_api/utils/sync.py index d44fdfb9..3e236d06 100644 --- a/bilibili_api/utils/sync.py +++ b/bilibili_api/utils/sync.py @@ -24,4 +24,4 @@ def sync(coroutine: Coroutine) -> Any: return asyncio.run(coroutine) else: with ThreadPoolExecutor() as executor: - return executor.submit(lambda: asyncio.run(coroutine)).result() + return executor.submit(asyncio.run, coroutine).result() From d0a3870dd07999a5c4aa31ac6d5cbaeb19993d82 Mon Sep 17 00:00:00 2001 From: LondonClass <43668206+LondonClass@users.noreply.github.com> Date: Sat, 13 Apr 2024 02:42:16 +0800 Subject: [PATCH 3/3] Update sync.py --- bilibili_api/utils/sync.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bilibili_api/utils/sync.py b/bilibili_api/utils/sync.py index 3e236d06..2a9c27d5 100644 --- a/bilibili_api/utils/sync.py +++ b/bilibili_api/utils/sync.py @@ -13,7 +13,7 @@ def sync(coroutine: Coroutine) -> Any: 同步执行异步函数,使用可参考 [同步执行异步代码](https://nemo2011.github.io/bilibili-api/#/sync-executor) Args: - coroutine (Coroutine): 执行协程函数所创建的协程对象 + coroutine (Coroutine): 执行异步函数所创建的协程对象 Returns: 该协程对象的返回值