我有兩個函式,都是異步的,由于 asyncio,它們在函式外部運行
但是,第二個函式在第一個函式中,它阻止了第一個函式的執行:(
請注意,這需要與大多數使用的 Python 版本兼容, 從 3.8 到最新版本)
async def func_2():
# basically does a request to a website and returns the status code
async def func_1():
tab = ["el0", "el1", ..., "el10"]
for i in range(len(tab)):
sys.stdout.write("\r[?] Progress: " tab[i % len(tab)])
sys.stdout.flush()
if i == 1:
result = await func_2()
await asyncio.sleep(0.4)
return result
while True:
func = asyncio.get_event_loop()
func_coroutine = func_1()
result = anim.run_until_complete(func_coroutine)
if result == 200:
print("Up")
else:
print("Down")
這func_1()只是為了讓用戶等待,但func_2()真正的作業是,花費的時間超過 0.4 秒??
所以我的問題是:是否可以在運行時func_1()繼續運行(并向用戶顯示內容)func_2()?
uj5u.com熱心網友回復:
做你想做的事,轉化func_2為任務。然后在里面回圈func_1直到func_2完成。這兩個任務將一起執行,表現出并發性。
我func_2用一個簡單的asyncio.sleep. 我使用狀態訊息的列印功能而不是stdout.write. 我列印最終結果,表明func_2任務result()方法可以訪問來自的資料。
我知道您的應用程式會做一些有用的事情,所以這個小腳本只是一個示例框架。
在 Win10 上使用 Python 3.10 測驗。
import asyncio
async def func_2():
await asyncio.sleep(2.0)
return 42
async def func_1():
my_task = asyncio.create_task(func_2())
i = 0
while not my_task.done():
print(f"\rProgress: el{i}", end='')
await asyncio.sleep(0.4)
i = 1
return my_task.result()
print('\nDone...', asyncio.run(func_1()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533694.html
