import urllib2
from multiprocessing.dummy import Pool as ThreadPool
urls = [
'http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/'
# etc..
]
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join()
import requests
s_city = "Petersburg,RU"
city_id = 0
appid = "APIKEY полученный после регистрации по ссылке https://home.openweathermap.org/users/sign_up"
try:
res = requests.get("http://api.openweathermap.org/data/2.5/find",
params={'q': s_city, 'type': 'like', 'units': 'metric', 'APPID': appid})
data = res.json()
cities = ["{} ({})".format(d['name'], d['sys']['country'])
for d in data['list']]
print("city:", cities)
city_id = data['list'][0]['id']
print('city_id=', city_id)
except Exception as e:
print("Exception (find):", e)
pass
try:
res = requests.get("http://api.openweathermap.org/data/2.5/weather",
params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'APPID': appid})
data = res.json()
print("conditions:", data['weather'][0]['description'])
print("temp:", data['main']['temp'])
print("temp_min:", data['main']['temp_min'])
print("temp_max:", data['main']['temp_max'])
except Exception as e:
print("Exception (weather):", e)
pass
try:
res = requests.get("http://api.openweathermap.org/data/2.5/forecast",
params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'APPID': appid})
data = res.json()
for i in data['list']:
print( i['dt_txt'], '{0:+3.0f}'.format(i['main']['temp']), i['weather'][0]['description'] )
except Exception as e:
print("Exception (forecast):", e)
pass
idle3
если не запустилось пиши sudo apt-get install idle3
while true
я бы выделил в функцию чтобы у цикла было какое то понятное название. И функции желательно называть так чтобы было понятно что они что то делают т.е. например не otmazki
а get_random_otmazka
и вместо weather
можно get_weather_in_user_city
. Желательно чтобы название функции было глаголом, а не существительным - так понятнее что это функция.vk = vk_api.VkApi(login='логин', password='пароль')
vk.auth()
values = {'out': 0, 'count': 1, 'time_offset': 10}
import asyncio
async def say(what, when):
await asyncio.sleep(when)
print(what)
async def stop_after(loop, when):
await asyncio.sleep(when)
loop.stop()
loop = asyncio.get_event_loop()
loop.create_task(say('first hello', 2))
loop.create_task(say('second hello', 1))
loop.create_task(say('third hello', 4))
loop.create_task(stop_after(loop, 3))
loop.run_forever()
loop.close()
import aiohttp
import asyncio
import async_timeout
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
app = web.Application()
app.router.add_get('/', handle)
app.router.add_get('/{name}', handle)
web.run_app(app)