我有代码,我想异步运行。我希望输出是以下内容之一:
Getting forecast 1
Getting forecast 2
Forecast 2 retrieved
Forecast 1 retrieved
或
Getting forecast 1
Getting forecast 2
Forecast 1 retrieved
Forecast 2 retrieved
然而,它似乎是同步运行的,因为每次运行它都会得到
Getting forecast 1
Getting forecast 2
Forecast 1 retrieved
Forecast 2 retrieved
代码附在下面:
import asyncio
import random
import pandas as pd
import numpy as np
async def get_forecast1():
print('Getting forecast 1')
await asyncio.sleep(random.randint(0 , 10))
return pd.DataFrame(np.zeros((2,2)))
async def retrieve_forecast1():
forecast1 = await get_forecast1()
print('Forecast 1 retrieved')
return forecast1
async def get_forecast2():
await asyncio.sleep(random.randint(0 , 10))
return pd.DataFrame(np.zeros((3,3)))
async def retrieve_forecast2():
print('Getting forecast 2')
forecast2 = await get_forecast2()
print('Forecast 2 retrieved')
return forecast2
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(retrieve_forecast1(), retrieve_forecast2()))
看来我是非常不幸的时候运行这个。我运行了大约10次,收到了相同的输出,这让我相信它是同步运行的。在运行了几次之后,我终于收到了第二个输出。