wikipedia pictures download example

This commit is contained in:
Luciano Ramalho
2015-02-02 02:56:14 -02:00
parent 73d98de6cd
commit ab6ce5b6a4
37 changed files with 2042 additions and 37 deletions

View File

@@ -0,0 +1,87 @@
"""
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send(20)
30
>>> adder.send(30)
60
>>> try:
... next(adder)
... except StopIteration as exc:
... result = exc.value
...
>>> result
Result(sum=60, terms=3, average=20.0)
Closing a coroutine:
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(1)
1
>>> adder.send(10)
11
>>> adder.close()
>>> try:
... next(adder)
... except StopIteration as exc:
... exc.value is None
...
True
"""
import sys
import collections
Result = collections.namedtuple('Result', 'sum terms average')
def adder_coro(initial=0):
total = initial
num_terms = 0
while True:
try:
term = yield total
except GeneratorExit:
break
if term is None:
break
total += term
num_terms += 1
return Result(total, num_terms, total/num_terms)
def prompt():
while True:
try:
term = float(input('+ '))
except ValueError:
break
yield term
def main(get_terms):
adder = adder_coro()
next(adder)
for term in get_terms:
adder.send(term)
try:
next(adder)
except StopIteration as exc:
result = exc.value
print(result)
if __name__ == '__main__':
if len(sys.argv) > 1:
get_terms = (float(n) for n in sys.argv[1:])
else:
get_terms = prompt()
main(get_terms)

View File

@@ -0,0 +1,96 @@
"""
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send(20)
30
>>> adder.send(30)
60
>>> try:
... next(adder)
... except StopIteration as exc:
... result = exc.value
...
>>> result
Result(sum=60, terms=3, average=20.0)
Closing a coroutine:
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(1)
1
>>> adder.send(10)
11
>>> adder.close()
>>> try:
... next(adder)
... except StopIteration as exc:
... exc.value is None
...
True
"""
import sys
import collections
def coroutine(func):
def primed_coroutine(*args, **kwargs):
coro = func(*args, **kwargs)
next(coro)
return coro
return primed_coroutine
Result = collections.namedtuple('Result', 'sum terms average')
@coroutine
def adder_coro(initial=0):
total = initial
num_terms = 0
while True:
try:
term = yield total
except GeneratorExit:
break
if term is None:
break
total += term
num_terms += 1
return Result(total, num_terms, total/num_terms)
def prompt():
while True:
try:
term = float(input('+ '))
except ValueError:
break
yield term
def main(get_terms):
adder = adder_coro()
for term in get_terms:
adder.send(term)
try:
adder.send(None)
except StopIteration as exc:
result = exc.value
print(result)
if __name__ == '__main__':
if len(sys.argv) > 1:
get_terms = (float(n) for n in sys.argv[1:])
else:
get_terms = prompt()
main(get_terms)

39
control/adder/soma.py Normal file
View File

@@ -0,0 +1,39 @@
if 'raw_input' in dir(__builtins__):
input = raw_input # para funcionar com Python 2
def ler_num():
num = input('+: ')
try:
num = float(num)
except ValueError:
return 0
return num
def somadora():
qt_parcelas = 0
total = 0
try:
while True:
parcela = yield
qt_parcelas += 1
total += parcela
print('parcelas: %d total: %d' % (qt_parcelas, total))
finally:
print('parcelas: %d total: %d media: %d' % (qt_parcelas, total, total/qt_parcelas))
def main():
coro = somadora()
next(coro)
while True:
item = ler_num()
if item:
coro.send(item)
else:
print('Fechando corotina...')
coro.close()
break
if __name__=='__main__':
main()

View File

@@ -0,0 +1,47 @@
if 'raw_input' in dir(__builtins__):
input = raw_input # para funcionar com Python 2
def ler_parcela():
parcela = input('+: ')
try:
parcela = float(parcela)
except ValueError:
return 0
return parcela
# decorator
def coro(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
next(g)
return g
return start
@coro
def somadora():
qt_parcelas = 0
total = 0
try:
while True:
parcela = yield
qt_parcelas += 1
total += parcela
print('parcelas: %d total: %d' % (qt_parcelas, total))
finally:
print('parcelas: %d total: %d media: %d' % (qt_parcelas, total, total/qt_parcelas))
def main():
coro = somadora()
while True:
parcela = ler_parcela()
if parcela:
coro.send(parcela)
else:
print('Fechando corotina...')
coro.close()
break
if __name__=='__main__':
main()

13
control/coro_demo.rst Normal file
View File

@@ -0,0 +1,13 @@
>>> def coroutine():
... print('coroutine started')
... x = yield
... print('coroutine received: {!r}'.format(x))
...
>>> coro = coroutine()
>>> next(coro)
coroutine started
>>> coro.send(42)
coroutine received: 42
Traceback (most recent call last):
...
StopIteration

View File

@@ -0,0 +1,13 @@
>>> def coroutine():
... print('coroutine started')
... x = yield
... print('coroutine received: {!r}'.format(x))
...
>>> coro = coroutine()
>>> next(coro)
coroutine started
>>> coro.send(42)
coroutine received: 42
Traceback (most recent call last):
...
StopIteration

24
control/demo_coro.py Normal file
View File

@@ -0,0 +1,24 @@
>>> def coro():
... print 'iniciando corotina...'
... while True:
... x = yield
... print 'recebido: ', x
... if x == -1: break
... print 'terminando corotina.'
...
>>> c = coro()
>>> next(c)
iniciando corotina...
>>> c.send(7)
recebido: 7
>>> c.send(3)
recebido: 3
>>> c.send(10)
recebido: 10
>>> c.send(-1)
recebido: -1
terminando corotina.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>

25
control/exemplo0.py Normal file
View File

@@ -0,0 +1,25 @@
def corrotina():
print('\t(corrotina) inciciando...')
x = yield
print('\t(corrotina) recebeu x: %r' % x)
y = yield
print('\t(corrotina) recebeu y: %r' % y)
print('\t(corrotina) terminando.')
def principal():
print('(principal) iniciando...')
co = corrotina()
print('(principal) invocando next(co)...')
next(co)
print('(principal) invocando co.send(88)...')
co.send(88)
try:
print('(principal) invocando co.send(99)...')
co.send(99)
# o print a seguir nunca vai acontecer
print('(principal) invocado co.send(99)')
except StopIteration:
print('(principal) a corotina nao tem mais valores a produzir')
principal()

27
control/exemplo1.py Normal file
View File

@@ -0,0 +1,27 @@
def corrotina():
print('\t(corrotina) inciciando...')
x = yield 1
print('\t(corrotina) recebeu x: %r' % x)
y = yield 2
print('\t(corrotina) recebeu y: %r' % y)
print('\t(corrotina) terminando.')
def principal():
print('(principal) iniciando...')
co = corrotina()
print('(principal) invocando next(co)...')
res = next(co)
print('(principal) produzido por next(co): %r' % res)
print('(principal) invocando co.send(88)...')
res2 = co.send(88)
print('(principal) produzido por co.send(88): %r' % res2)
try:
print('(principal) invocando co.send(99)...')
res3 = co.send(99)
# o print a seguir nunca vai acontecer
print('(principal) produzido por co.send(99): %r' % res3)
except StopIteration:
print('(principal) a corotina nao tem mais valores a produzir')
principal()

26
control/guido/guido0.py Normal file
View File

@@ -0,0 +1,26 @@
"""
Exemplo adaptado da mensagem do Guido van Rossum em:
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
http://bit.ly/yieldfrom
>>> principal(ger1())
OK
42
Visualização no PythonTutor: http://goo.gl/FQWq2F
"""
def ger1():
val = yield 'OK'
print(val)
yield # para evitar o StopIteration
def principal(g):
print(next(g))
g.send(42)
# auto-teste
import doctest
doctest.testmod()

29
control/guido/guido1.py Normal file
View File

@@ -0,0 +1,29 @@
"""
Exemplo adaptado da mensagem do Guido van Rossum em:
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
http://bit.ly/yieldfrom
>>> principal(ger2())
OK
42
Visualização no PythonTutor: http://goo.gl/pWrlkm
"""
def ger1():
val = yield 'OK'
print(val)
yield # para evitar o StopIteration
def ger2():
yield from ger1()
def principal(g):
print(next(g))
g.send(42)
# auto-teste
import doctest
doctest.testmod()

30
control/guido/guido1b.py Normal file
View File

@@ -0,0 +1,30 @@
"""
Exemplo adaptado da mensagem do Guido van Rossum em:
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
http://bit.ly/yieldfrom
>>> principal(ger2())
OK
None
Visualização no PythonTutor: http://goo.gl/61CUcA
"""
def ger1():
val = yield 'OK'
print(val)
yield # para evitar o StopIteration
def ger2():
for i in ger1():
yield i
def principal(g):
print(next(g))
g.send(42)
# auto-teste
import doctest
doctest.testmod()

31
control/guido/guido2.py Normal file
View File

@@ -0,0 +1,31 @@
"""
Exemplo adaptado da mensagem do Guido van Rossum em:
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
http://bit.ly/yieldfrom
>>> principal_susto(ger1())
OK
Bu!
Visualização no PythonTutor: http://goo.gl/m6p2Bc
"""
def ger1():
try:
val = yield 'OK'
except RuntimeError as exc:
print(exc)
else:
print(val)
yield # para evitar o StopIteration
def principal_susto(g):
print(next(g))
g.throw(RuntimeError('Bu!'))
# auto-teste
import doctest
doctest.testmod()

35
control/guido/guido3.py Normal file
View File

@@ -0,0 +1,35 @@
"""
Exemplo adaptado da mensagem do Guido van Rossum em:
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
http://bit.ly/yieldfrom
>>> principal_susto(ger2())
OK
Bu!
Visualização no PythonTutor: http://goo.gl/QXzQHS
"""
def ger1():
try:
val = yield 'OK'
except RuntimeError as exc:
print(exc)
else:
print(val)
yield # para evitar o StopIteration
def ger2():
yield from ger1()
def principal_susto(g):
print(next(g))
g.throw(RuntimeError('Bu!'))
# auto-teste
import doctest
doctest.testmod()

20
control/http_cli0.py Normal file
View File

@@ -0,0 +1,20 @@
# adaptado de:
# https://github.com/feihong/tulip-talk/blob/master/examples/2-tulip-download.py
import asyncio
import aiohttp
@asyncio.coroutine
def download(url):
response = yield from aiohttp.request('GET', url)
for k, v in response.items():
print('{}: {}'.format(k, v[:80]))
data = yield from response.read()
print('\nReceived {} bytes.\n'.format(len(data)))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
url = 'https://www.cia.gov/library/publications/the-world-factbook/geos/br.html'
coroutine = download(url)
loop.run_until_complete(coroutine)

90
control/mirror.py Normal file
View File

@@ -0,0 +1,90 @@
"""
A "mirroring" ``stdout`` context.
While active, the context manager reverses text output to
``stdout``::
# BEGIN MIRROR_DEMO_1
>>> from mirror import LookingGlass
>>> with LookingGlass() as what: # <1>
... print('Alice, Kitty and Snowdrop') # <2>
... print(what)
...
pordwonS dna yttiK ,ecilA # <3>
YKCOWREBBAJ
>>> what # <4>
'JABBERWOCKY'
# END MIRROR_DEMO_1
This exposes the context manager operation::
# BEGIN MIRROR_DEMO_2
>>> from mirror import LookingGlass
>>> manager = LookingGlass() # <1>
>>> manager
<mirror.LookingGlass object at 0x2a578ac>
>>> monster = manager.__enter__() # <2>
>>> monster == 'JABBERWOCKY' # <3>
eurT
>>> monster
'YKCOWREBBAJ'
>>> manager
>ca875a2x0 ta tcejbo ssalGgnikooL.rorrim<
>>> manager.__exit__(None, None, None) # <4>
>>> monster
'JABBERWOCKY'
# END MIRROR_DEMO_2
The context manager can handle and "swallow" exceptions.
# BEGIN MIRROR_DEMO_3
>>> from mirror import LookingGlass
>>> with LookingGlass():
... print('Humpty Dumpty')
... x = 1/0 # <1>
... print('END') # <2>
...
ytpmuD ytpmuH
Please DO NOT divide by zero!
>>> with LookingGlass():
... print('Humpty Dumpty')
... x = no_such_name # <1>
... print('END') # <2>
...
Traceback (most recent call last):
...
NameError: name 'no_such_name' is not defined
# END MIRROR_DEMO_3
"""
# BEGIN MIRROR_EX
class LookingGlass:
def __enter__(self): # <1>
import sys
self.original_write = sys.stdout.write # <2>
sys.stdout.write = self.reverse_write # <3>
return 'JABBERWOCKY' # <4>
def reverse_write(self, text): # <5>
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_value, traceback): # <6>
import sys # <7>
sys.stdout.write = self.original_write # <8>
if exc_type is ZeroDivisionError: # <9>
print('Please DO NOT divide by zero!')
return True # <10>
# <11>
# END MIRROR_EX

64
control/mirror_gen.py Normal file
View File

@@ -0,0 +1,64 @@
"""
A "mirroring" ``stdout`` context manager.
While active, the context manager reverses text output to
``stdout``::
# BEGIN MIRROR_GEN_DEMO_1
>>> from mirror_gen import looking_glass
>>> with looking_glass() as what: # <1>
... print('Alice, Kitty and Snowdrop')
... print(what)
...
pordwonS dna yttiK ,ecilA
YKCOWREBBAJ
>>> what
'JABBERWOCKY'
# END MIRROR_GEN_DEMO_1
This exposes the context manager operation::
# BEGIN MIRROR_GEN_DEMO_2
>>> from mirror_gen import looking_glass
>>> manager = looking_glass() # <1>
>>> manager # doctest: +ELLIPSIS
<contextlib._GeneratorContextManager object at 0x...>
>>> monster = manager.__enter__() # <2>
>>> monster == 'JABBERWOCKY' # <3>
eurT
>>> monster
'YKCOWREBBAJ'
>>> manager # doctest: +ELLIPSIS
>...x0 ta tcejbo reganaMtxetnoCrotareneG_.biltxetnoc<
>>> manager.__exit__(None, None, None) # <4>
>>> monster
'JABBERWOCKY'
# END MIRROR_GEN_DEMO_2
"""
# BEGIN MIRROR_GEN_EX
import contextlib
@contextlib.contextmanager # <1>
def looking_glass():
import sys
original_write = sys.stdout.write # <2>
def reverse_write(text): # <3>
original_write(text[::-1])
sys.stdout.write = reverse_write # <4>
yield 'JABBERWOCKY' # <5>
sys.stdout.write = original_write # <6>
# END MIRROR_GEN_EX

96
control/mirror_gen_exc.py Normal file
View File

@@ -0,0 +1,96 @@
"""
A "mirroring" ``stdout`` context manager.
While active, the context manager reverses text output to
``stdout``::
# BEGIN MIRROR_GEN_DEMO_1
>>> from mirror_gen import looking_glass
>>> with looking_glass() as what: # <1>
... print('Alice, Kitty and Snowdrop')
... print(what)
...
pordwonS dna yttiK ,ecilA
YKCOWREBBAJ
>>> what
'JABBERWOCKY'
# END MIRROR_GEN_DEMO_1
This exposes the context manager operation::
# BEGIN MIRROR_GEN_DEMO_2
>>> from mirror_gen import looking_glass
>>> manager = looking_glass() # <1>
>>> manager # doctest: +ELLIPSIS
<contextlib._GeneratorContextManager object at 0x...>
>>> monster = manager.__enter__() # <2>
>>> monster == 'JABBERWOCKY' # <3>
eurT
>>> monster
'YKCOWREBBAJ'
>>> manager # doctest: +ELLIPSIS
>...x0 ta tcejbo reganaMtxetnoCrotareneG_.biltxetnoc<
>>> manager.__exit__(None, None, None) # <4>
>>> monster
'JABBERWOCKY'
# END MIRROR_GEN_DEMO_2
The context manager can handle and "swallow" exceptions.
# BEGIN MIRROR_GEN_DEMO_3
>>> from mirror_gen import looking_glass
>>> with looking_glass():
... print('Humpty Dumpty')
... x = 1/0 # <1>
... print('END') # <2>
...
ytpmuD ytpmuH
Please DO NOT divide by zero!
>>> with looking_glass():
... print('Humpty Dumpty')
... x = no_such_name # <1>
... print('END') # <2>
...
Traceback (most recent call last):
...
NameError: name 'no_such_name' is not defined
# END MIRROR_GEN_DEMO_3
"""
# BEGIN MIRROR_GEN_EX
import contextlib
@contextlib.contextmanager # <1>
def looking_glass():
import sys
original_write = sys.stdout.write # <2>
def reverse_write(text): # <3>
original_write(text[::-1])
sys.stdout.write = reverse_write # <4>
msg = ''
try:
yield 'JABBERWOCKY' # <5>
except ZeroDivisionError: # <6>
msg = 'Please DO NOT divide by zero!' # <7>
except:
raise # <8>
finally:
sys.stdout.write = original_write # <9>
if msg:
print(msg) # <10>
# END MIRROR_GEN_EX

12
control/referencias.txt Normal file
View File

@@ -0,0 +1,12 @@
What's New in Python 2.5 - PEP 342: New Generator Features
http://docs.python.org/release/2.5/whatsnew/pep-342.html
PEP 342 -- Coroutines via Enhanced Generators
http://www.python.org/dev/peps/pep-0342/
PEP 380 -- Syntax for Delegating to a Subgenerator
http://www.python.org/dev/peps/pep-0380/
Coroutines For the Working Python Developer
http://sdiehl.github.io/coroutine-tutorial/