我正在尝试以下代码:
import asyncio
@asyncio.coroutine
def func_normal():
print("A")
yield from asyncio.sleep(5)
print("B")
return 'saad'
@asyncio.coroutine
def func_infinite():
i = 0
while i<10:
print("--"+str(i))
i = i+1
return('saad2')
loop = asyncio.get_event_loop()
tasks = [
asyncio.async(func_normal()),
asyncio.async(func_infinite())]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
我无法弄清楚如何从这些函数中获取变量中的值。我不能这样做:
asyncio.async(a = func_infinite())
因为这会使它成为关键字参数。我该如何完成这项工作?
答案 0 :(得分:33)
协同程序按原样工作。只需使用loop.run_until_complete()
和call asyncio.gather()
to collect multiple results的返回值:
#!/usr/bin/env python3
import asyncio
@asyncio.coroutine
def func_normal():
print('A')
yield from asyncio.sleep(5)
print('B')
return 'saad'
@asyncio.coroutine
def func_infinite():
for i in range(10):
print("--%d" % i)
return 'saad2'
loop = asyncio.get_event_loop()
tasks = func_normal(), func_infinite()
a, b = loop.run_until_complete(asyncio.gather(*tasks))
print("func_normal()={a}, func_infinite()={b}".format(**vars()))
loop.close()
--0
--1
--2
--3
--4
--5
--6
--7
--8
--9
A
B
func_normal()=saad, func_infinite()=saad2
答案 1 :(得分:6)
loop.run_until_complete
返回您传递给它的函数返回的值。因此,它将返回asyncio.wait
:
import asyncio
@asyncio.coroutine
def func_normal():
print("A")
yield from asyncio.sleep(5)
print("B")
return 'saad'
@asyncio.coroutine
def func_infinite():
i = 0
while i<10:
print("--"+str(i))
i = i+1
return('saad2')
loop = asyncio.get_event_loop()
tasks = [
asyncio.async(func_normal()),
asyncio.async(func_infinite())]
done, _ = loop.run_until_complete(asyncio.wait(tasks))
for fut in done:
print("return value is {}".format(fut.result()))
loop.close()
输出:
A
--0
--1
--2
--3
--4
--5
--6
--7
--8
--9
B
return value is saad2
return value is saad
您也可以直接从tasks
数组访问结果:
print(tasks[0].result())
print(tasks[1].result())
答案 2 :(得分:2)
如果你想在coroutine结束时使用coroutine返回的任何值,你可以将未来的对象传递给coro并通过计算值更新这个未来。一旦未来更新,它会将future.result()传递给与给定的未来绑定的回调函数。请参阅以下代码:
import asyncio
async def func_normal(future):
print("A")
await asyncio.sleep(5)
print("B")
# return 'saad'
future.set_result('saad')
async def func_infinite(future):
i = 0
while i<10:
print("--"+str(i))
i = i+1
# return('saad2')
future.set_result('saad2')
def got_result(future):
print(future.result())
loop = asyncio.get_event_loop()
future1 = asyncio.Future()
future2 = asyncio.Future()
future1.add_done_callback(got_result)
future2.add_done_callback(got_result)
# Coros are automatically wrapped in Tasks by asyncio.wait()
coros = [
func_normal(future1),
func_infinite(future2)]
loop.run_until_complete(asyncio.wait(coros))
loop.close()
使用单个参数调用回调函数 - 它与之绑定的未来对象。如果你需要将更多参数传递给回调,请使用functools包中的partial:
future1.add_done_callback(functools.partial(print, "future:", argin))
将致电
print("future:", argin)