-------------------------------- aio | -------------------------------- * ѧϰ×ÊÁÏ http://www.jianshu.com/p/b5e347b3a17c * ʼþÇý¶¯ÐÎIO * 3.5°æ±¾ÒÔǰ 1,ÔÚÉú³ÉÆ÷Éϱêʶע½â @asyncio.coroutine È»ºóÔÚcoroutineÄÚ²¿ÓÃyield fromµ÷ÓÃÁíÒ»¸ö coroutine ʵÏÖÒì²½²Ù×÷ 2,´´½¨ event_loop ¶ÔÏó(asyncio.get_event_loop()) 3,Ö´ÐÐ event_loop ¶ÔÏóµÄ run_until_complete()º¯Êý,°ÑÉú³ÉÆ÷ʵÀý×÷Ϊ²ÎÊý´«µÝ½øÈ¥ * ¸Ãº¯Êý²ÎÊýÒ²¿ÉÒÔÊÇ asyncio.wait(tast_arr) º¯Êý·µ»ØÖµ * ±íʾһ´ÎÐÔÖ´Ðжà¸öÉú³ÉÆ÷ * demo : tasks = [hello(), hello()] loop.run_until_complete(asyncio.wait(tasks)) 4,¹Ø±Õ event_loop ¶ÔÏó (close()) * 3.5 °æ±¾ÒÔºó * ÓÃasyncioÌṩµÄ @asyncio.coroutine ¿ÉÒÔ°ÑÒ»¸ögenerator±ê¼ÇΪcoroutineÀàÐÍ,È»ºóÔÚcoroutineÄÚ²¿ÓÃyield fromµ÷ÓÃÁíÒ»¸ö coroutine ʵÏÖÒì²½²Ù×÷ * ΪÁ˼ò»¯²¢¸üºÃµØ±êʶÒì²½IO£¬´ÓPython 3.5¿ªÊ¼ÒýÈëÁËеÄÓï·¨asyncºÍawait,¿ÉÒÔÈÃcoroutineµÄ´úÂë¸ü¼ò½àÒ×¶Á * Çë×¢Òâ,asyncºÍawaitÊÇÕë¶ÔcoroutineµÄÐÂÓï·¨,ҪʹÓÃеÄÓï·¨,Ö»ÐèÒª×öÁ½²½¼òµ¥µÄÌæ»» * ²½Öè 1,Éú³ÉÆ÷²»Ê¹Óà @asyncio.coroutine ×¢½â±êʶ,¶øÊ¹Óà async ¹Ø¼ü×Ö±êʶ 2,²»Ê¹Óà yield from Óï¾ä,¶øÊ¹Óà await ¹Ø¼ü×Ö * demo import asyncio async def demo(name): print('[%s]1'%(name)) r = await asyncio.sleep(2) print('[%s]2'%(name)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([demo('Kevin'),demo('Litch')])) * event_loop api create_task() run_until_complete() run_forever() create_server() close() stop() -------------------------------- aio-ÈëÃÅ | -------------------------------- import asyncio @asyncio.coroutine def hello(): print("Hello world!") # Òì²½µ÷ÓÃasyncio.sleep(1): r = yield from asyncio.sleep(1) print("Hello again!") # »ñÈ¡EventLoop: loop = asyncio.get_event_loop() # Ö´ÐÐcoroutine loop.run_until_complete(hello()) loop.close() ''' Hello world! Hello again! ''' -------------------------------- aio-½ø½× | -------------------------------- import threading import asyncio @asyncio.coroutine def hello(): print('Hello world! (%s)' % threading.currentThread()) yield from asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread()) loop = asyncio.get_event_loop() tasks = [hello(), hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close() ''' Hello world! (<_MainThread(MainThread, started 6956)>) Hello world! (<_MainThread(MainThread, started 6956)>) Hello again! (<_MainThread(MainThread, started 6956)>) Hello again! (<_MainThread(MainThread, started 6956)>) ''' -------------------------------- aio-½á¹û»Øµ÷ | -------------------------------- import asyncio async def demo(var): asyncio.sleep(1) return var * var # ´´½¨ loop loop = asyncio.get_event_loop() # ´´½¨ task task = asyncio.ensure_future(demo(5)) # taskÌí¼Ó¼àÌý,Ôڻص÷º¯ÊýÖе÷ÓÃÐÎ²ÎµÄ result() »ñÈ¡½á¹ûÐÅÏ¢ # taskºÍ»Øµ÷ÀïµÄx¶ÔÏó,ʵ¼ÊÉÏÊÇͬһ¸ö¶ÔÏó task.add_done_callback(lambda x : print('result:%s'%(x.result()))) # Ö´ÐÐÈÎÎñ loop.run_until_complete(asyncio.wait([task])) loop.close() -------------------------------- aio-server | -------------------------------- import asyncio class SimpleProtocol(asyncio.Protocol): # еÄÁ¬½Ó def connection_made(self, transport): self.transport = transport # ÊÕµ½ÐµÄÊý¾Ý def data_received(self, data): # °ÑÊÕµ½µÄÊý¾ÝÏìÓ¦¸ø¿Í»§¶Ë self.transport.write(data) # Á¬½Ó¶Ï¿ª def connection_lost(self, exception): #server.close() pass # ´´½¨ event_loop loop = asyncio.get_event_loop() # ´´½¨·þÎñÆ÷ʵÀý server = loop.run_until_complete(loop.create_server(SimpleProtocol, 'localhost', 1024)) # ÔËÐÐ loop.run_until_complete(server.wait_closed()) -------------------------------- aio-ʵս | -------------------------------- # ¾É°æÊµÏÖ import asyncio @asyncio.coroutine def wget(host): print('wget %s...' % host) connect = asyncio.open_connection(host, 80) reader, writer = yield from connect header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host writer.write(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() if line == b'\r\n': break print('%s header > %s' % (host, line.decode('utf-8').rstrip())) # Ignore the body, close the socket writer.close() loop = asyncio.get_event_loop() tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']] loop.run_until_complete(asyncio.wait(tasks)) loop.close() # аæÊµÏÖ import asyncio async def demo(target): reader, writer = await asyncio.open_connection(*target) header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n'%(target[1]) writer.write(bytes(header,'UTF_8')) await writer.drain() while True: line = await reader.readline() if line == b'\r\n': break print('%s header > %s' %(target[1], line.decode('utf-8').rstrip())) writer.close() loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([demo(('www.qq.com',80)),demo(('www.javaweb.io',80))])) loop.close() -------------------------------- aio-asyncio | -------------------------------- wait() gather() * ¸ú wait() Ò»Ñù,²»¹ýËü»á·µ»ØÒ»¸ö[],ÀïÃæµÄÿ¸öÔªËØÊÇÿ¸öгÌÖ´ÐÐÍê±ÏºóµÄ½á¹û ensure_future() get_event_loop() as_completed() open_connection(ip, port) * ´ò¿ªÒ»¸öÒì²½IOÁ¬½Ó * ·µ»Ø (reader,writer) Ôª×é