Palestra UFSC/UNESC 09/2006
Apresentação introdutória de Python realizada em Santa Catarina na UFSC e na UNESC em Setembro de 2006.
Python: O que, quando, como e por que ?
| Evento: | Palestra UFSC |
|---|---|
| Author: | Rodrigo Dias Arruda Senra |
| Data: | 29 de setembro de 2006 |
Eu sou apenas um rapaz latino-americano...
- IC/Unicamp - desde 1992
- GPr Sistemas - desde 1996
- Palestras SL - desde 2001
Vamos falar de que ?
- O Graal do Desenvolvedor
- A tecno-diversidade
- Contextualizando Python
- Expandindo seu "Vocabulário Ofidiglota"
- Fazendo um pouco de tudo em Python (com 10 linhas)
- Zope
- Plone (cenas dos próximos capítulos)
O Graal do Desenvolvedor
- Rapidez no Ciclo de Desenvolvimento
- Qualidade
- Facilidade
- Legibilidade
- Estabilidade
- Portabilidade
- Extensibilidade
- Escalabilidade
- Interoperabilidade
- Customização
A Eterna Busca pela Ferramenta Perfeita
Fonte:http://people.mandriva.com/~prigaux/language-study/diagram.png
TIOBE Programming Community Index
Baseado no Google, MSN e Yahoo! (Fonte:http://www.tiobe.com/tpci.htm)
Java
import java.io.*;
import java.util.*;
import java.text.*;
public class sumcol {
public static void main(String[] args) {
int count = 0;
String line;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
while ((line = in.readLine()) != null) {
count = count + Integer.parseInt(line);
}
} catch (IOException e) { }
System.out.println(Integer.toString(count));
C#
using System;
class App {
public static int Main(String[] args) {
int count = 0;
for (String line = Console.In.ReadLine();
line != null;
line = Console.In.ReadLine())
{ count += System.Convert.ToInt32(line); }
Console.WriteLine(count.ToString());
return(0);
}
Python
import sys
def main():
count = 0
for line in sys.stdin.readlines():
count += int(line)
print count
Palavras Reservadas
and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in Obs: Comparação Python(29), Java(52) e C#(77)
Cobras no Google
Python has been an important part of Google since the beginning, and remains so as the system grows and evolved. Today dozens of Google engineers use Python, and we're looking for more people with skils in sthis language.
—Peter Norvig (Director of Search Quality @ Google)
Edsinger's Domo (MIT)
15 node [and growing] Debian Linux cluster running a
mixture of C/C++/Python and utilizing the Yarp and
pysense robot libraries.
Fonte:http://people.csail.mit.edu/edsinger/domo.htm
Industrial Light & Magic
ILM created its own compositor with a plugin architecture for doing motion picture editing rather than choosing a commercial package. The compositor plugins are in Python. We're a big Python shop...and MEL. MEL is the Maya scripting language.
—Robert Weaver (Sequence Supervisor)
Fonte: http://www.linuxjournal.com/article/6011
Histórias de Sucesso (Software Livre)
- Zope/Plone
- BitTorrent
- Blender
- Gnumeric
- Gimp
- MoinMoin
- Mailman
- Chandler
- OpenOffice
O que é Python ?
- Interpretada
- Interativa
- Tipagem Forte e Dinâmica
- Orientada a Objetos
- Very High-Level Language (VHLL)
Por que Python ?
- Poderosas Estruturas de Dados Nativas
- Fácil Aprendizagem e Manutenção
- Disponível com código aberto e sem custo
- Interoperabilidade com C/C++/Java/Delphi/Objective-C/Lua/Ruby
- Extensa Biblioteca Padrão
- Multi-plataforma
Onde ?
- Unix: HP-UX, Solaris, Linux (freqüentemente pré-instalada), ...
- Mac OSX (pré-instalada)
- Windows: 9x, Me, 2K, XP (ctypes, win32all)
- Nokia Série 60 e Maemo
- PalmOS (PipPy) :o(
Interoperabilidade
- CPython (onde existir um compilador C ISO/IEC 9899:1990)
- Jython (máquina virtual Java)
- PyPy (Python implementado em Python)
- Python for .NET [Brian Lloyd]
- IronPython (suportado pela M$)
- Python for Delphi
- LunaticPython (interoperando com Lua)
- Ruby/Python (em Ruby importar módulos Python)
Como
- não existem delimitadores de bloco => Identação
- Compilação implícita de bytecode
- Threads, OO, herança múltipla, tratamento de exceções e gc
- Reflexão computacional
Funções Aninhadas
def participacao_lucro(bonus):
def soma(salario):
return salario+bonus
return soma
bonus_junior = participacao_lucro(100)
bonus_pleno = participacao_lucro(500)
bonus_senior = participacao_lucro(1000)
beltrano = bonus_junior(1300)
fulano = bonus_pleno(2000)
fulano, beltrano
(2500, 1400)
Geradores
def gera_id(semente):
i = semente
while 1:
i += 1
yield i
novo_id = gera_id(13)
novo_id.next()
14
novo_id.next()
15
Geradores
Entidades que geram iteradores!
def fibonacci():
n1, n2 = 1, 1
while 1:
n1, n2, result = n1+n2, n1, n2
yield resultdef pares():
f = fibonacci()
l2 = f.next()
while 1:
l1 = f.next()
yield l1, l2
l2 = l1
Abrangência de Listas (List Comprehensions)
[ <expressão> for <variáveis> in <sequência> <condicionais> ]
>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i**2 for i in x]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [i**2 for i in x if i%2==0]
[0, 4, 16, 36, 64]
Orientação a Objetos
class Trabalhador(object):
def __init__(self, numero):
self.numero = numero
t = Trabalhador(321)
class Eleitor(object):
def __init__(self, titulo, zona, sessao):
self.titulo = titulo
self.zona = zona
self.sessao = sessao
e = Eleitor(titulo='1234', zona='13', sessao='14')
Herança Múltipla
class CidadaoPleno(Trabalhador, Eleitor):
def __init__(self, **kw):
Trabalhador.__init__(self, **kw)
Eleitor.__init__(self, **kw)
self.rg = kw['rg']
self.cpf = kw['cpf']
c = CidadaoPleno(titulo='1234', zona='13', sessao='14',
numero=1234,
rg='234356', cpf='127638175')
Integração com a Linguagem C
// Em C
include <Python.h>
static PyObject *
meu_system(PyObject *self, PyObject *args)
{
char *command; int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}
// Em Python <!-- PyConbrasil -->
<div style="margin-bottom: 1em">
<img tal:replace="structure here/banner.gif" />
</div>
import meu
status = meu.system("ls -l")
Canivete-Suíço Anabolizado
- Bancos de Dados : ODBC, MySQL, Postgres, DCOracle, SQLServer, sqlite, gadfly, ZODB/Durus, PyDO, Metakit
- Protocolos de Rede : Twisted, asyncore, htmllib, SimpleHTTPServer, urllib, ftplib, poplib, smtplib, telnetlib
- GUI : Tkinter, wxPython, PyGTk, PyQt, PyKDE, Pythonwin
- Ciência : Numarray, SciPy, BioPython, AstroPy, Py2R/SPlus
- Proc. de Imagens : PIL, PythonMagick, Gimp-python
- XML : PyXML, 4Suite, ElementTree, RDFLib, Cwm
- Web : ZOPE, CherryPy, Webware, Quixote, PSP, mod_python, Nevow, Django, TurboGears
- IDE : Emacs, vi, idle, PyDev (Eclipse), SPE, Pythonwin, Komodo, BlackAdder, WingIDE, PyScripter
Manipulação de Imagens (PIL)
import os, sys
from PIL import Image, ImageDraw, ImageFont, ImageFilter
fontpath = "/Users/rsenra/src/python/multimedia/pilfonts"
def txt2img(label, imgformat="PNG", rotate_angle=0):
"""Gera imagem rotacionada"""
font = ImageFont.load(os.path.join(fontpath,"timR24.pil"))
imgOut = Image.new("RGBA", (20,49), (255,255,255))
draw = ImageDraw.Draw(imgOut)
sizex, sizey = draw.textsize(label, font=font)
imgOut = imgOut.resize((sizex,sizey))
draw = ImageDraw.Draw(imgOut)
draw.text((0, 0), label, fill=(0,0,0), font=font)
if rotate_angle:
imgOut = imgOut.rotate(rotate_angle)
return imgOut
txt2img("belex", rotate_angle=90).save("belex.png")
import os; os.system("open belex.png")
Networking (Twisted)
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from time import asctime
class TimeServer(Protocol):
def dataReceived(self, data):
if data.strip() in ('fim','q','quit','adios'):
reactor.stop()
else:
self.transport.write(asctime())
def main():
f = Factory()
f.protocol = TimeServer
reactor.listenTCP(8000, f)
reactor.run()
main()
Web Services
from SOAPpy import SOAPProxy
from SOAPpy import Types
google = SOAPProxy( 'http://api.google.com/search/beta2',
'urn:GoogleSearch')
results = google.doGetCachedPage('Pd...oX', 'www.owls.org')
of = open('cached_page_response.html', 'w')
of.write(results)
of.close()
Bancos de Dados Relacionais (Postgres)
from psycopg import *
o = connect("dbname=teste user=fulano")
c = o.cursor()
c.execute("SELECT * FROM nome_da_tabela")
row = c.fetchone()
print row
l = [ ('valor_1', 'fulano', 0),
('valor_2', 'beltrano', 5),
('valor_3', 'ciclano', 15)]
c.executemany("INSERT INTO outra_tabela VALUES"
" (%s, %s, %s)", l)
c.commit()
ZODB
from ZODB.DB import DB
from ZODB.FileStorage import FileStorage
from ZEO import ClientStorage
import transaction
from ZODB.POSException import ConflictError
storage = FileStorage('demo.fs')
#storage = ClientStorage.ClientStorage(('192.168.0.1',9999))
db = DB(storage)
conn = db.open()
root = conn.root()
root.x = 1
transaction.commit()
root.x = 2
transaction.abort()
- http://python.org
- http://www.pythonbrasil.com.br
- http://aspn.activestate.com/ASPN/Python/Cookbook/
- http://www.onlamp.com/python/
- http://www.python-eggs.org/links.html
- http://www.jython.org
- http://zope.org
- http://plone.org
- http://www.tchezope.org
Referências Bibliográficas
- Python in a Nutshell: *Alex Martelli* (O'Reilly)
- Python Cookbook: *Alex Martelli, David Ascher* (O'Reilly)
- Python Programming on Win32: Mark Hammond (O'Reilly)
- Jython Essential: Noel Rappin, Samuele Pedroni (O'Reilly)
- Foundations of Python Network Programming: John Goerzen (Apress)
Resumindo: O canivete-suiço!
- Python é uma linguagem de alto nível, ágil, madura e moderna
- Alta produtividade a baixo custo
- Comunidade ativa
- Fartura de documentação
- E divertida ;o)
Obrigado a todos pela atenção !
Perguntas, Críticas, Comentários ?
Rodrigo Senra
http://rodrigo.senra.nom.br
IC-Unicamp
http://www.ic.unicamp.br
GPr Sistemas
http://www.gpr.com.br

