2016-11-12 3 views
1

asyncio 파이썬 모듈을 가지고 놀고 있는데 간단한 코드에 어떤 문제가 있는지 알지 못합니다. 비동기 적으로 타스크를 실행하지 않습니다.Asyncio가 작업을 비동기 적으로 실행하지 않습니다.

#!/usr/bin/env python3  

import asyncio 
import string  


async def print_num(): 
    for x in range(0, 10): 
     print('Number: {}'.format(x)) 
     await asyncio.sleep(1)  

    print('print_num is finished!')  

async def print_alp(): 
    my_list = string.ascii_uppercase  

    for x in my_list: 
     print('Letter: {}'.format(x)) 
     await asyncio.sleep(1)  

    print('print_alp is finished!')  


async def msg(my_msg): 
    print(my_msg) 
    await asyncio.sleep(1)  


async def main(): 
    await msg('Hello World!') 
    await print_alp() 
    await msg('Hello Again!') 
    await print_num()  


if __name__ == '__main__': 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(main()) 
    loop.close() 

다음은 스크립트가 호출 될 때 출력입니다 :

Hello World! 
Letter: A 
Letter: B 
Letter: C 
Letter: D 
Letter: E 
Letter: F 
Letter: G 
Letter: H 
Letter: I 
Letter: J 
Letter: K 
Letter: L 
Letter: M 
Letter: N 
Letter: O 
Letter: P 
Letter: Q 
Letter: R 
Letter: S 
Letter: T 
Letter: U 
Letter: V 
Letter: W 
Letter: X 
Letter: Y 
Letter: Z 
print_alp is finished! 
Hello Again! 
Number: 0 
Number: 1 
Number: 2 
Number: 3 
Number: 4 
Number: 5 
Number: 6 
Number: 7 
Number: 8 
Number: 9 
print_num is finished! 

답변

2

코드는 순차적으로 실행, 그래서 당신은 순차적으로 함수를 호출한다. await this은 "this이 돌아 오기 위해을 대기해야 함"을 의미한다는 것을 기억하십시오 (그러나 그 동안에는 this이 실행을 일시 중지하도록 선택하면 이미 다른 곳에서 시작된 다른 작업이 실행될 수 있습니다).

async def main(): 
    await msg('Hello World!') 
    task1 = asyncio.ensure_future(print_alp()) 
    task2 = asyncio.ensure_future(print_num()) 
    await asyncio.gather(task1, task2) 
    await msg('Hello Again!') 

또한 asyncio.gather 함수의 문서를 참조하십시오 :

비동기 작업을 실행하려면

, 당신은 할 필요가있다. 또는 asyncio.wait을 사용할 수도 있습니다.

1

당신은 coroutines '아이'에 대한 순차적으로 행동하지만 그들은 coroutines '이웃'에 대한 비동기 적으로 행동한다는 것입니다 await 진술과 혼란의 일반적인 소스를 발생하고 있습니다. 예를 들어

:

import asyncio 

async def child(): 
    i = 5 
    while i > 0: 
     print("Hi, I'm the child coroutine, la la la la la") 
     await asyncio.sleep(1) 
     i -= 1 

async def parent(): 
    print("Hi, I'm the parent coroutine awaiting the child coroutine") 
    await child() # this blocks inside the parent coroutine, but not the neighbour 
    print("Hi, I'm the parent, the child coroutine is now done and I can stop waiting") 

async def neighbour(): 
    i = 5 
    while i > 0: 
     await asyncio.sleep(1) 
     print("Hi, I'm your neighbour!") 
     i -= 1 

async def my_app(): 
    # start the neighbour and parent coroutines and let them coexist in Task wrappers 
    await asyncio.wait([neighbour(), parent()]) 

if __name__ == '__main__': 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(my_app()) 

출력 :

Hi, I'm the parent coroutine awaiting the child coroutine 
Hi, I'm the child coroutine, la la la la la 
Hi, I'm the child coroutine, la la la la la 
Hi, I'm your neighbour! 
Hi, I'm the child coroutine, la la la la la 
Hi, I'm your neighbour! 
Hi, I'm the child coroutine, la la la la la 
Hi, I'm your neighbour! 
Hi, I'm the child coroutine, la la la la la 
Hi, I'm your neighbour! 
Hi, I'm the parent, the child coroutine is now done and I can stop waiting 
Hi, I'm your neighbour! 

Process finished with exit code 0 
관련 문제