如何从异步/等待函数返回值



我有一个循环,当它完成时,它返回一个数据帧。然后在应用程序的其他地方处理此数据帧。从广义上讲,在序列码中,它看起来是这样的:

import pandas as pd
def print_int_seq():
col_1 = []
col_2 = []
for i in range(10):
col_1.append(i)
col_2.append(2*i)
print(i)
return pd.DataFrame({'col_1': col_1, 'col_2': col_2})
def run_seq():
df = print_int_seq()
print(df)
if __name__ == "__main__":
run_seq()

我现在想要另一个函数,它将与返回数据帧的循环异步运行。我不知道该怎么做(从异步/等待函数返回一个值(。如果我不需要返回任何东西,程序(带有两个异步函数(可能会是这样的:

import pandas as pd
from datetime import datetime
import asyncio
async def print_time(con):
while True:
print(datetime.now().time())
await asyncio.sleep(1)
async def print_int():
# I would like this to return the full 10x2 dataframe 
col_1 = []
col_2 = []
for i in range(10):
col_1.append(i)
col_2.append(2*i)
print(i)
await asyncio.sleep(1)
async def main():
# how can I catch and process the 10x2 dataframe returned by print_int()?
await asyncio.gather(
print_time(con),
print_int(),
)
if __name__ == "__main__":
asyncio.run(main())

我如何编辑上面的脚本,以便在循环耗尽时捕获数据帧并在另一个函数中处理它?另一个异步函数中的循环永远不会结束,这有关系吗?

首先也是最重要的一点:async非常模仿函数的行为-如果你想让它们返回一个值,只需添加一个带有你想返回的值的return语句:

async def print_int():
# I would like this to return the full 10x2 dataframe 
col_1 = []
col_2 = []
for i in range(10):
...
return pd.Dataframe(...)

第二:asyncio.gather只是简单地返回一个序列,其中包含已执行任务的所有返回值,为此,它必须等到所有";聚集的";任务返回。如果其他任务是有限的,并且或多或少在同一时间完成,你会这样做:

async def main():
result1, result2 = await asyncio.gather(
print_time(con),
print_int(),
)

当你计划有一个根本不会结束的并发例程时,asyncio.gather并不是最好的选择:只需为两个协同例程创建一个任务,然后等待你想要的任务的结果:

async def main():
# this will get the other co-routine running in the background:
asyncio.create_task(print_time(con))

result = await print_int()

最新更新