File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr.bin.env python 3
2+ # -*- coding: utf-8 -*-
3+
4+ '''
5+ 练习python的async/await
6+ async:相当于asyncio.coroutine,可以用这个替换这个更加方便
7+ await:相当于yield form,把这个改成await即可替代
8+ 以上都是在python3.5版本以上才有的
9+ '''
10+
11+ __author__ = 'sergiojune'
12+ import asyncio
13+
14+
15+ async def hello (): # 这样就是相当于一个coroutine了
16+ print ('hello world' )
17+ await asyncio .sleep (1 )
18+ print ('hello again' )
19+
20+
21+ # loop = asyncio.get_event_loop()
22+ # loop.run_until_complete(hello())
23+ # loop.close()
24+
25+
26+ # 两个协程
27+ # loop = asyncio.get_event_loop()
28+ # loop.run_until_complete(asyncio.wait([hello(), hello()]))
29+ # loop.close()
30+
31+
32+ # 再用这个方法连接搜狐新浪和网易
33+ async def wegt (host ):
34+ print ('wegt %s ' % host )
35+ # 连接
36+ connect = asyncio .open_connection (host , 80 )
37+ reader , writer = await connect
38+ header = 'GET/HTTP/1.0\r \n Host:%s\r \n \r \n ' % host
39+ writer .write (header .encode ('utf-8' ))
40+ await writer .drain () # 相当于刷新缓存
41+ while True :
42+ line = await reader .readline ()
43+ if line == b'\r \n ' :
44+ print ()
45+ break
46+ print ('%s header > %s' % (host , line .decode ('utf-8' ).strip ()))
47+ connect .close ()
48+
49+
50+ loop = asyncio .get_event_loop ()
51+ loop .run_until_complete (asyncio .wait ([wegt (host ) for host in ['www.sina.com.cn' , 'www.sohu.com' , 'www.163.com' ]]))
52+ loop .close ()
You can’t perform that action at this time.
0 commit comments