Python - Descubre El Poder Del Lenguaje Scripting de Moda en La Comunidad Open Source
Python - Descubre El Poder Del Lenguaje Scripting de Moda en La Comunidad Open Source
. . . .
ESIDE
Python: descubre el poder del
lenguaje scripting de moda en la
comunidad open source
Dr. Diego Lz. de Ipia Gz. de Artaza
http://paginaspersonales.deusto.es/dipina
Universidad de Deusto
. . . .
ESIDE
l otro lenguaje de programaci!n
"ue empieza con #P#
0imple y poderoso
De scripting
@pen source
De prop!sito general
0trong typing
Python
=ython
Python es ideal:
rpm %iv
python!&'%!&'&'%pydotor(&i')*&rpm
Universidad de Deusto
. . . .
ESIDE
Fsando Python desde l/nea
comando
Fn comando simple:
888 print "Hola Mundo"
Hola Mundo
888
Para salir del int9rprete .trlCD 'en Linu8* o .trlCM 'en Linu8* o:
888 import sys
888 sys&exit(
+
Universidad de Deusto
. . . .
ESIDE
jecutando programa
holamundo.py
Los blo"ues son indicados por tabulaci!n "ue sigue a una sentencia
acabada en #:#. .j. 'blo:ue&py*:
# .omentarios de l;nea se indi.an .on .ar<.ter =#=
name > "-ie(o1" # asi(na.i?n de valor a variable
if name >> "-ie(o":
print "@upa -ie(o"
else:
print "ABuiCn eresD"
print "EFo eres -ie(o!"
+ python blo:ue&py
ABuiCn eresD
EFo eres -ie(o!
Universidad de Deusto
. . . .
ESIDE
Identi$icadores
Palabras reser%adas:
&a( strings
888 print r=LnLL= # no se =es.apa= Ln
Listas 26
Para usar una lista como una pila2 se pueden usar append y pop:
OOO items.append'TTT*
OOO items HCS2 Q2 R2 TTTI
OOO items.pop'*
TTT
OOO items HCS2 Q2 RI
Universidad de Deusto
. . . .
ESIDE
Bipos de datos ?
.j. 'condicional.py*
: > I
h > 1
if : Z h :
print "primer test pasado"
else:
print "se(undo test pasado"
888 python .ondi.ional&py
primer test pasado
j. bu.le&py
for x in ran(e(1,1:
print x
+ python bu.le&py
1 ! ' I
Por ejemplo:
reply > =repite=
5hile reply >> =repite=:
print =Hola=
reply > ra5Ginput(=Nntrodu.e "repite" para
ha.erlo de nuevo: =
Hola
Nntrodu.e "repite" para ha.erlo de nuevo:
repite
Hola
Nntrodu.e "repite" para ha.erlo de nuevo: adi?s
Universidad de Deusto
. . . .
ESIDE
Uunciones
?isualizar/a:
ar(s: (=aaa=, =bbb=
H5ar(s: "=ar(1=: =...=, =ar(!=: =ddd=$
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ar(/: "un primer ar(umento"
ar(s: (=aaa=, =bbb=
H5ar(s: "=ar(1=: =...=, =ar(!=: =ddd=$
Universidad de Deusto
. . . .
ESIDE
.lases
Fna clase contiene una colecci!n de m9todos. .ada m9todo contiene como primer
par+metro 'self* "ue hace re$erencia a un objeto
?isualizar/a:
\asi. %% name: ManXana
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\asi. %% name: FaranKa
Ppe.ial %% upper name: F@T@FS@& Nt=s edible&
Universidad de Deusto
. . . .
ESIDE
8cepciones
?isualizar/a:
Ms(: mi mensaKe de error
Universidad de Deusto
. . . .
ESIDE
,!dulos
.j. modulo&py:
def one(a:
print "in one"
def t5o (.:
print "in t5o"
Fso de un m!dulo:
888 import modulo
888 dir(modulo # lista .ontenidos m?dulo
2=GGbuiltinsGG=, =GGdo.GG=, =GGfileGG=, =GGnameGG=,
=one=, =t5o=6
888 modulo&one(!
in one
Universidad de Deusto
. . . .
ESIDE
,!dulos II
?isualizar/a:
.lass #1
.lass #!
print (printredire.t&py*
Lo cual %isualizar/a:
(sho5G(lobal nombre: ManXana
(setG(lobal nombre: FaranKa
(sho5G(lobal nombre: FaranKa
Universidad de Deusto
. . . .
ESIDE
0erializaci!n de objetos
,y0VLdb 'http://source$orge.net/projects/mys"lCpython*
tc.
Universidad de Deusto
. . . .
ESIDE
jemplo programaci!n ED en
Python con ,y0VL I
.reamos una base de datos de nombre deusto a la "ue podemos hacer login con
usuario deusto y pass(ord deusto, a travCs del si(uiente PBJ:
4TO@7O -@7@\@PO deusto#
3T@F7 @J7OT, POJO47,NFPOT7,Q,-@7O,-OJO7O,4TO@7O,-TR,
RF deusto&[
7R deusto_=W=
N-OF7NYNO- \U =deusto=#
3T@F7 @J7OT, POJO47,NFPOT7,Q,-@7O,-OJO7O,4TO@7O,-TR,
RF deusto&[
7R deusto_lo.alhost
N-OF7NYNO- \U =deusto=#
Qse deusto#
4TO@7O 7@\JO OMOF7RP(N- int(11 FR7 FQJJ ,TNM@TU `OU,
FRM\TO M@T4H@T(!1/, JR4@JN]@4NRF M@T4H@T(!1/, YO4H@ bi(int(!/,
-OP4TN,4NRF M@T4H@T(!1/#
NFPOT7 NF7R OMOF7RP M@JQOP (/, =POM@F@ OPN-O=, =OPN-O%-OQP7R=, /,
=4harla sobre ,ython=#
Universidad de Deusto
. . . .
ESIDE
jemplo programaci!n ED en
Python con ,y0VL II
# db/a..esodbeventos&py
import MyPBJdb, time, strin(, Gmys:l, Gmys:lGex.eptions
def exe.utePBJ4ommand(.ursor, .ommand:
result > ""
.ommand > strin(&strip(.ommand
if len(.ommand:
try:
.ursor&exe.ute(.ommand # OKe.uta el .omando
if strin(&lo5er(.ommand&starts5ith(=sele.t=:
# si es una sele.t &&&
lines > .ursor&fet.hall( # re.uperar todos los
resultados
for line in lines:
for .olumn in line:
if .olumn >> Fone:
result > result + =null =
else:
result > result + str(.olumn + = =
result > result + =Ln=
ex.ept Gmys:lGex.eptions&,ro(rammin(Orror, e:
print e
sys&exit(
return result
Universidad de Deusto
. . . .
ESIDE
jemplo programaci!n ED en
Python con ,y0VL III
if GGnameGG >> =GGmainGG=:
db>MyPBJdb&.onne.t(host>"lo.alhost",user>"deusto", pass5d>"deusto",
db>"deusto"
.ursor > db&.ursor(
exe.utePBJ4ommand(.ursor, "update eventos set fe.ha>" + str(time&time
([1///
results > exe.utePBJ4ommand(.ursor, "sele.t [ from eventos"
print results
print results&split( # .rear una lista y la visualiXa
del .ursor
?isualizando lo siguiente:
+ python a..esodbeventos&py
/ POM@F@ OPN-O OPN-O%-OQP7R 1/V)0/111**1/ 4harla sobre ,ython
2=/=, =POM@F@=, =OPN-O=, =OPN-O%-OQP7R=, =1/V)0/111**1/=, =4harla=,
=sobre=, =,ython=6
Universidad de Deusto
. . . .
ESIDE
Programaci!n de e8presiones
regulares I
http://(((.onlamp.com/pub/a/python/KNNQ/NK/KR/pythonZser%erZpages.htm
l
Z!d .(i%bin/psp/holamundo&psp %%8
Zhtml8
ZW
if form&hasGHey(=nombre=:
saludo > =Hola, Ws!= W form2=nombre=6&.apitaliXe(
else:
saludo > =Hola mundo!=
# end
W8
Zh18ZW> saludo W8Z/h18
Zp8Qsa parametro =nombre= para re.ibir un saludo, e&(&
holamundo&pspDnombre>-ie(oZ/p8
Z/html8
Universidad de Deusto
. . . .
ESIDE
Programaci!n en Y,L con 0AY
De$ine K m9todos:
maHeGparser(2parserGlist6
parse(filenameGorGstream, handler2,
errorGhandler6
http://py8ml.source$orge.net/topics/
Universidad de Deusto
. . . .
ESIDE
jemplo D@, I
# xml/eKemplo-RM&py
# OKe.utar: python eKemplo-RM&py 4artelera&xml
#!/usr/bin/env python
import xml&dom&minidom, sys
.lass ,eli.ula:
def GGinitGG(self, .odi(o, titulo, dire.tor, a.tores:
self&.odi(o > .odi(o
self&titulo > titulo
self&dire.tor > dire.tor
self&a.tores > a.tores
def GGreprGG(self:
return "4odi(o: " + str(self&.odi(o + " % titulo: " +
self&titulo + " % dire.tor: " + self&dire.tor + " % a.tores: " +
self&a.tores
.lass ,eli.ula-RM,arser:
def GGinitGG(self, filename:
self&dom > xml&dom&minidom&parse(filename
self&peli.ulas > 26
Universidad de Deusto
. . . .
ESIDE
jemplo D@, II
def (et,eli.ulas(self:
if not self&peli.ulas:
peli.ulaFodes > self&dom&(etOlements\y7a(Fame(",eli.ula"
num,elis > len(peli.ulaFodes
for i in ran(e(num,elis:
peli.ula > peli.ulaFodes&item(i
# Te.uperar los attributes de .ada nodo ,eli.ula
peli@ttribs > peli.ula&attributes
.odi(o > peli@ttribs&(etFamedNtem(".odi(o"&nodeMalue
titulo > peli@ttribs&(etFamedNtem("titulo"&nodeMalue
dire.tor > peli@ttribs&(etFamedNtem("dire.tor"&nodeMalue
a.tores > peli@ttribs&(etFamedNtem("a.tores"&nodeMalue
self&peli.ulas&append(,eli.ula
(.odi(o,titulo,dire.tor,a.tores
return self&peli.ulas
if GGnameGG >> =GGmainGG=:
dom,arser > ,eli.ula-RM,arser(sys&ar(v216
for peli in dom,arser&(et,eli.ulas(:
print peli
Universidad de Deusto
. . . .
ESIDE
Programaci!n distribuida:
.@&EA con omni@&Epy
,U7HRF,@7H>ZomniRT\py%install%dir8/lib/python#
ZomniRT\py%install%dir8LlibLx)*G5in'!
,@7H>+,@7H:>ZomniRT\py%install%dir8/bin/x)*G5in'!
J-GJN\T@TUG,@7H>ZomniRT\py%install%
dir8LlibLZplatform8
(8Python 'http://(((.(8python.org/*
Python(in 'http://(((.python.org/(indo(s/python(in/*
PyGB\ 'http://(((.pygt<.org/*
PyVt 'http://(((.ri%erban<computing.co.u</py"t/*
Universidad de Deusto
. . . .
ESIDE
jemplo B<inter I
# (ui/tHinter5at.h&py
from 7Hinter import [
import time, sys
.lass Ptop9at.h(Yrame:
""" Nmplements a stop 5at.h frame 5id(et& """
def GGinitGG(self, parent>Fone, [[H5:
Yrame&GGinitGG(self, parent, H5
self&Gstart > /&/
self&Gelapsedtime > /&/
self&Grunnin( > /
self×tr > Ptrin(Mar(
self&maHe9id(ets(
def maHe9id(ets(self:
""" MaHe the time label& """
l > Jabel(self, textvariable>self×tr
self&Gset7ime(self&Gelapsedtime
l&pa.H(fill>e, expand>FR, pady>!, padx>!
def Gupdate(self:
""" Qpdate the label 5ith elapsed time& """
self&Gelapsedtime > time&time( % self&Gstart
self&Gset7ime(self&Gelapsedtime
self&Gtimer > self&after(1/, self&Gupdate
def Gset7ime(self, elap:
""" Pet the time strin( to Minutes:Pe.onds:Hundreths """
minutes > int(elap/*/
se.onds > int(elap % minutes[*/&/
hse.onds > int((elap % minutes[*/&/ % se.onds[1//
self×tr&set(=W/!d:W/!d:W/!d= W (minutes, se.onds, hse.onds
Universidad de Deusto
. . . .
ESIDE
jemplo B<inter II
def Ptart(self:
""" Ptart the stop5at.h, i(nore if runnin(& """
if not self&Grunnin(:
self&Gstart > time&time( % self&Gelapsedtime
self&Gupdate(
self&Grunnin( > 1
def Ptop(self:
""" Ptop the stop5at.h, i(nore if stopped& """
if self&Grunnin(:
self&afterG.an.el(self&Gtimer
self&Gelapsedtime > time&time( % self&Gstart
self&Gset7ime(self&Gelapsedtime
self&Grunnin( > /
def Teset(self:
""" Teset the stop5at.h& """
self&Gstart > time&time(
self&Gelapsedtime > /&/
self&Gset7ime(self&Gelapsedtime
if GGnameGG >> =GGmainGG=: root > 7H(
s5 > Ptop9at.h(root
s5&pa.H(side>7R,
\utton(root, text>=Ptart=, .ommand>s5&Ptart&pa.H(side>JOY7
\utton(root, text>=Ptop=, .ommand>s5&Ptop&pa.H(side>JOY7
\utton(root, text>=Teset=, .ommand>s5&Teset&pa.H(side>JOY7
\utton(root, text>=Buit=, .ommand>sys&exit(/&pa.H(side>JOY7
root&mainloop(
Universidad de Deusto
. . . .
ESIDE
jemplo de GFI con Pm(
Universidad de Deusto
. . . .
ESIDE
jemplo (8Python I
#!/usr/bin/env python
# (ui/(8Python0emana0ID.py
GGauthorGG > "-ie(o Npifa Zdipina_eside&deusto&es8"
import 5x
.lass Yrame(5x&Yrame:
"""4lase frame :ue visualiXa una ima(en&"""
def GGinitGG(self, ima(e, parent>Fone, id>%1,
pos>5x&-efault,osition, title>=EHola, semaneros
OPN-O!=:
"""4rea un Yrame y visualiXa ima(en&"""
temp > ima(e&4onvert7o\itmap(
siXe > temp&3et9idth(, temp&3etHei(ht(
5x&Yrame&GGinitGG(self, parent, id, title, pos, siXe
self&bmp > 5x&Ptati.\itmap(parent>self, id>%1,
bitmap>temp
Universidad de Deusto
. . . .
ESIDE
jemplo (8Python II
.lass @pp(5x&@pp:
"""4lase apli.a.i?n&"""
def RnNnit(self:
5x&Nnit@llNma(eHandlers(
ima(e > 5x&Nma(e(=semanaeside&Kp(=, 5x&\N7M@,G7U,OGS,O3
self&frame > Yrame(ima(e
self&frame&Pho5(
self&Pet7op9indo5(self&frame
return 7rue
def main(:
app > @pp(
app&MainJoop(
if GGnameGG >> =GGmainGG=:
main(
http://(((.jython.org/do(nload.html
http://(((.jython.org/applets/inde8.html
http://(((.jython.org/docs/useja%a.html
Universidad de Deusto
. . . .
ESIDE
jemplo =ython: EuttonDemo
# http://555&Kython&or(/applets/button&html
from Kava import a5t, applet
.lass \utton-emo(applet&@pplet:
def init(self:
self&b1 > a5t&\utton(=-isable middle button=,
a.tion,erformed>self&disable
self&b! > a5t&\utton(=Middle button=
self&b' > a5t&\utton(=Onable middle button=, enabled>/,
a.tion,erformed>self&enable
self&add(self&b1
self&add(self&b!
self&add(self&b'
def enable(self, event:
self&b1&enabled > self&b!&enabled > 1
self&b'&enabled > /
def disable(self, event:
self&b1&enabled > self&b!&enabled > /
self&b'&enabled > 1
Universidad de Deusto
. . . .
ESIDE
.asos de 98ito de Python
http://(((.python.org/K.L.L/
https://source$orge.net/projects/py(inLK/
http://source$orge.net/projects/mys"lCpython
http://(((.mys"l.com/do(nloads/mys"lCQ.N.html
omni@&Epy
http://omniorb.source$orge.net/
(8Python K.Q:
http://(((.(8python.org/do(nload.phpAbinaries
=ython K.S
http://(((.jython.org/do(nload.html