Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
jszheng committed Feb 23, 2016
1 parent bfcbd8b commit e2791f4
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 0 deletions.
20 changes: 20 additions & 0 deletions asyncio_chain_coroutine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import asyncio


@asyncio.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield from asyncio.sleep(1.0)
return x + y


@asyncio.coroutine
def print_sum(x, y):
result = yield from compute(x, y)
print("%s + %s = %s" % (x, y, result))
yield from asyncio.sleep(1.0)
print('end')

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
13 changes: 13 additions & 0 deletions asyncio_coroutine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
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(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
21 changes: 21 additions & 0 deletions asyncio_future.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import asyncio

@asyncio.coroutine
def slow_operation(future):
print('start slow_operation')
yield from asyncio.sleep(1)
print('set future done')
future.set_result('Future is done!')

def got_result(future):
print(future.result())
loop.stop()

loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.async(slow_operation(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
24 changes: 24 additions & 0 deletions asyncio_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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()

0 comments on commit e2791f4

Please sign in to comment.