在Python Asyncio上,我试图从一个函数返回值到另一个函数



在Python Asyncio上,我试图从一个函数返回一个值给另一个。

所以当if语句在function "check"= True返回的will值

将移出"print"func。

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 None当一个函数完成它的最后一个语句,即当return data['state']没有在check()中执行。在这种情况下,什么都不打印-如果不正确,请调整代码。

当然,您应该只启动print_it协程,而不启动checks


如果出于某种原因确实需要并发运行函数,请使用Queue。生产者将数据放入队列,当数据可用时,消费者获得该值。