1import asyncio
2
3async def print_B(): #Simple async def
4 print("B")
5
6async def main_def():
7 print("A")
8 await asyncio.gather(print_B())
9 print("C")
10asyncio.run(main_def())
11
12# The function you wait for must include async
13# The function you use await must include async
14# The function you use await must run by asyncio.run(THE_FUNC())
15
16
17
1#will sleep the current corutien for set numner of seconds
2import asyncio
3await asyncio.sleep(1)
4
5
1import asyncio
2
3async def main():
4 print('Hello ...')
5 await asyncio.sleep(1)
6 print('... World!')
7
8# Python 3.7+
9asyncio.run(main())
10
11# output
12"""
13Hello ...
14...World!
15"""
16# with a 1 second wait time after Hello ...
1import asyncio
2from PIL import Image
3import urllib.request as urllib2
4
5async def getPic(): #Proof of async def
6 pic = Image.open(urllib2.urlopen("https://c.files.bbci.co.uk/E9DF/production/_96317895_gettyimages-164067218.jpg"))
7 return pic
8
9async def main_def():
10 print("A")
11 print("Must await before get pic0...")
12 pic0 = await asyncio.gather(getPic())
13 print(pic0)
14asyncio.run(main_def())
1import signal
2import sys
3import asyncio
4import aiohttp
5import json
6
7loop = asyncio.get_event_loop()
8client = aiohttp.ClientSession(loop=loop)
9
10async def get_json(client, url):
11 async with client.get(url) as response:
12 assert response.status == 200
13 return await response.read()
14
15async def get_reddit_top(subreddit, client):
16 data1 = await get_json(client, 'https://www.reddit.com/r/' + subreddit + '/top.json?sort=top&t=day&limit=5')
17
18 j = json.loads(data1.decode('utf-8'))
19 for i in j['data']['children']:
20 score = i['data']['score']
21 title = i['data']['title']
22 link = i['data']['url']
23 print(str(score) + ': ' + title + ' (' + link + ')')
24
25 print('DONE:', subreddit + '\n')
26
27def signal_handler(signal, frame):
28 loop.stop()
29 client.close()
30 sys.exit(0)
31
32signal.signal(signal.SIGINT, signal_handler)
33
34asyncio.ensure_future(get_reddit_top('python', client))
35asyncio.ensure_future(get_reddit_top('programming', client))
36asyncio.ensure_future(get_reddit_top('compsci', client))
37loop.run_forever()
38