我正在尝试实现一个能够运行函数(这需要很长时间才能完成)的程序。
我对python中的线程和代码流的理解是非常有限的,而且我很难理解一些没有显式异步等待关键字的方法(例如PyGithub库,它发出请求,让我在没有等待的情况下等待结果)如何在线程和异步进程中工作。
下面是我想要做的一个程序的例子(不完全是正确的实现):
from asyncio import create_task, sleep
# loading animation
async def loading():
delay, chars, i = .06, '|/—\\', 0
while True:
print(chars[i % len(chars)], end='\r') # print one char out of <chars[x]> at one instance of time
i += 1
await sleep(delay)
# Executing given function while displaying a loading-animation on console
# :param exec: a given function to run while loading (type: (...) -> any).
# :param msgBefore: a message to display before starting the process (type: str).
# :rtype: ReturnType<exec>
async def execWhileLoading(exec, msgBefore):
# print before-msg
print(msgBefore)
# fetch data while loading
loading_t = create_task(loading()) # load animation on another thread
result = exec() # returns a result after some time (NOT asyncronous)
# fetching is done - cancel loading animation
loading_t.cancel() # cancel animation thread
print(' ', end='\r') # hide loading-char from console
return result这里我们有两个简单的函数。每当我们试图在控制台上运行一个很好的加载动画的时候,execWhileLoading函数就会被调用。loading作为异步函数被调用,在屏幕上显示和更改动画文本。
我的问题是exec函数。无论是正常的还是异步的,我都不知道在哪种情况下我应该做什么。如何正确地集成它,以便在加载函数运行的同时执行exec函数?当exec函数解析(以某种方式)时,它应该停止。
希望我的问题很清楚。
发布于 2022-11-11 20:58:29
更改函数execWhileLoading中的一行,以在执行器中运行加载函数。默认的执行器( ThreadPoolExecutor)在另一个线程中运行函数,但是您可能希望使用ProcessPoolExecutor。该方法返回一个awaitable,因此它需要在等待表达式中使用。
请参阅这里的标准库文档。https://docs.python.org/3/library/asyncio-eventloop.html#executing-code-in-thread-or-process-pools
非常漂亮的是,请将变量名"exec“更改为其他内容(exec是一个内置函数,并将其作为变量名来隐藏正常功能)。
async def execWhileLoading(func, msgBefore):
# print before-msg
print(msgBefore)
# fetch data while loading
loading_t = create_task(loading()) # load animation on another thread
# returns a result after some time (NOT asyncronous)
result = await asyncio.get_event_loop().run_in_executor(None, func)
# fetching is done - cancel loading animation
loading_t.cancel() # cancel animation thread
print(' ', end='\r') # hide loading-char from console
return resulthttps://stackoverflow.com/questions/74399077
复制相似问题