簡體   English   中英

在 Python Asyncio 上,我試圖將值從一個函數返回到另一個函數

[英]On Python Asyncio I am trying to return a value from one function to another

在 Python Asyncio 上,我試圖將一個函數的值返回到另一個函數。

因此,當 func "check" 末尾的 if 語句為 True 時,返回的 will 值

將去“打印”功能。

async def check(i):
        async with aiohttp.ClientSession() as session:
            url = f'https://pokeapi.co/api/v2/pokemon/{i}'
            async with session.get(url) as resp:
                data = await resp.text()
                if data['state'] == 'yes':
                    return data['state']
                ## how do i keeping the structre of the asyncio and pass this result to the "print" function



async def print(here should be the return of "check" funtion is there is):
        print()
        await asyncio.sleep(0)


async def main():
    for i in range(0,5):
        await asyncio.gather(check(i),
                             print() )

謝謝你 (-:

您的代碼將同步運行所有內容。 您需要稍微重構一下,才能從 asyncio 中看到任何價值。

async def check(i):
    async with aiohttp.ClientSession() as session:
        url = f'https://pokeapi.co/api/v2/pokemon/{i}'
        async with session.get(url) as resp:
            data = await resp.text()
            if data['state'] == 'yes':
                return data['state']

async def main():
    aws = [check(i) for i in range(5)]
    results = await asyncio.gather(*aws)
    for result in results:
        print(result)

這將允許您的 aiohttp 請求異步運行。 假設print實際上只是內置函數的包裝器,那么您不需要它,只需使用內置函數即可。

但是,如果print實際上執行其他操作,則應使用asyncio.as_completed而不是asyncio.gather

async def my_print(result):
    print(result)
    await asyncio.sleep(0)

async def main():
    aws = [check(i) for i in range(5)]
    for coro in asyncio.as_completed(aws):
        result = await coro
        await my_print(result)

簡單的解決辦法:不要同時運行這兩個函數。 其中一個顯然需要另一個來完成。

async def print_it(i):
    value = await check(i)
    if value is not None:
        print(value)

當函數完成其最后一條語句時,即當return data['state']未在check()執行時,有一個隱式return None 在這種情況下,不會打印任何內容 - 如果不正確,請調整代碼。

當然,你應該只啟動print_it協程,而不啟動checks


如果出於某種原因確實需要同時運行這些函數,請使用Queue 生產者將數據放入隊列,消費者在可用時獲取值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM