希望python在异步功能完成之前返回数据

时间:2020-11-06 10:22:16

标签: python asynchronous

我该怎么写才能达到预期的效果?

所需的打印:1(从此处开始小睡功能)2(在这里返回99)3

import asyncio

async def nap():
    await asyncio.sleep(4)
    print(3)

async def main():
    print(1)
    
    #I don't want to wait for func nap to complete. I just want nap to start here and finish the sleep after '2' is printed. Is that possible?
    await nap()
    print(2)
    return 99

# Python 3.7+
asyncio.run(main())

当前打印: 1(从此处开始小睡功能)3 2(此处返回99)

1 个答案:

答案 0 :(得分:0)

import time
from concurrent.futures import ThreadPoolExecutor

def nap():
    print('Nap started...')
    time.sleep(4)
    print(3)

def main():
    print(1)
    executor = ThreadPoolExecutor(max_workers=100)
    task1 = executor.submit(nap)
    print(2)
    return 99

if __name__ == '__main__':
    data_returned_before_tasks_complete = main()
    print('data_returned_before_tasks_complete: ', data_returned_before_tasks_complete)