Академический Документы
Профессиональный Документы
Культура Документы
PyGuide.....................................................................................................................................................7
................................................................................................................................................8
Chapter1(ProgrammingConcepts)....................................................................................................10
Chapter2(IntroductiontoPython).....................................................................................................12
Chapter3(Basics)................................................................................................................................14
List..................................................................................................................................................15
ListComprehension........................................................................................................................18
Tuples..............................................................................................................................................19
Strings.............................................................................................................................................20
UserString.......................................................................................................................................22
Dictionaries....................................................................................................................................26
Conditions.......................................................................................................................................29
Loops..............................................................................................................................................32
while...........................................................................................................................................32
for...............................................................................................................................................33
Don'tbreakupwithme..............................................................................................................35
Ourdancewillcontinue.............................................................................................................36
Chapter4(Functions&Procedures)....................................................................................................38
DRY:Don'tRepeatYourself...........................................................................................................38
To*argsornotto*args..................................................................................................................44
To**kwargsornotto**kwargs....................................................................................................45
Goingglobal...................................................................................................................................46
Lambda/AnonymousFunctions......................................................................................................48
Iterable............................................................................................................................................50
Generator.........................................................................................................................................51
Iterator.............................................................................................................................................51
Chapter5(OOP)..................................................................................................................................56
..............................................................................................................................................56
Fields..........................................................................................................................................56
Methods......................................................................................................................................56
Properties...................................................................................................................................56
Encapsulation.............................................................................................................................57
__init__......................................................................................................................................57
get/set.........................................................................................................................................59
properties....................................................................................................................................61
Magicmethods...........................................................................................................................63
OperatorOverloading.....................................................................................................................67
BTW,..Enums................................................................................................................................70
Chapter6(Inheritance)........................................................................................................................74
MultipleInheritance........................................................................................................................81
Chapter7(Exceptions,Errors)............................................................................................................84
Chapter8(IO).....................................................................................................................................89
BasicIO..........................................................................................................................................89
os,os.path.......................................................................................................................................92
FilePointer......................................................................................................................................96
Chapter9(Modules/Packages:ChargingaBattery)...........................................................................101
FindingNemo...............................................................................................................................102
FirstModule.................................................................................................................................102
Packages.......................................................................................................................................104
Platform.........................................................................................................................................106
Chapter10(Databases)......................................................................................................................110
Python/MySQL.............................................................................................................................110
PySQLite.......................................................................................................................................116
ORMs............................................................................................................................................123
Storm........................................................................................................................................124
SQLObject...............................................................................................................................126
SQLAlchemy............................................................................................................................128
Chapter11(ParsingData)..................................................................................................................130
XMLingwithPython....................................................................................................................130
1minidom...............................................................................................................................132
2SAX.....................................................................................................................................136
3Expatundercover..................................................................................................................141
HappyMapper...........................................................................................................................143
ElementTree..............................................................................................................................147
HTMLingwithPython..................................................................................................................148
BeautifulSoup..........................................................................................................................149
ParsingCSVFiles.........................................................................................................................150
ConfigParser.................................................................................................................................153
Regex:...........................................................................................................................................155
.....................................................................................................................156
Gimmeusage!...........................................................................................................................157
GIMMEoptparser!...................................................................................................................157
os.system..................................................................................................................................160
subprocess.................................................................................................................................161
Replacer........................................................................................................................................162
Chapter12(Networking)....................................................................................................................171
SimpleServer................................................................................................................................171
SimpleClient.................................................................................................................................173
SocketServer..................................................................................................................................175
AppwithaBUG..........................................................................................................................182
FTPing.........................................................................................................................................203
XMLRPCwhat?...........................................................................................................................205
DocXMLRPCServer.....................................................................................................................208
QuoteoftheDay...........................................................................................................................212
Chapter13(PythonontheWEB).....................................................................................................218
Grok...............................................................................................................................................218
Webpy...........................................................................................................................................230
TheBigThree...............................................................................................................................234
Pylons.......................................................................................................................................234
TurboGears...............................................................................................................................242
Chapter14(ExtendingPython).........................................................................................................251
PureC............................................................................................................................................251
Swig..............................................................................................................................................260
ctypes............................................................................................................................................261
Chapter15(FunctionalPython)......................................................................................................266
functools.......................................................................................................................................267
itertools.........................................................................................................................................269
Chapter16(PyInotify).......................................................................................................................274
............................................................................................................................................274
Watches.........................................................................................................................................275
Events............................................................................................................................................275
Goingon........................................................................................................................................275
PDir...............................................................................................................................................276
Event.............................................................................................................................................276
Chapter17(GUI)...............................................................................................................................278
PyGTK..........................................................................................................................................278
Gladizer.........................................................................................................................................316
RadwithGlade(Gqamoos)...........................................................................................................319
HowToGladizerguiTK?...............................................................................................................334
...............................................................................................................................................340
! .....................................................................................................................................340
.......................................................................................................................................340
.................................................................................................................................340
!...........................................................................................................................................341
..............................................................................................................................................341
PyGuide
Python
- -
.. !
Programming-Fr34ks.NET
Ahmed Youssef
GNU FDL "
(
guru.python[at]gmail.com
.
)Chapter1(ProgrammingConcepts
Programming
) ( ..
0 1
Programming Language
.. 0
1 ! .. ..
..
...
0 1
(:
Programming Language
" "
Source Code
Text
Debugging
..
Debugging (:
Compiled vs Interpreted
Windows exe. exe
Executable ..
C Pascal exe
)
( compiled exe
Python, Perl py. pl.
Text Editor - - Source Code
) (Interpreter
Source Code
Compiled Languages C
Compile Source Code
Windows recompile Linux ..
Interpreted Languages Source Code
Recompile archS
:
Interpreted Languages
Compiled Language
)Chapter2(IntroductiontoPython
Python High Level Programming
Language "" 1989 Guido Van Rossum
Python
-1
-2
-3 Portability - -Platform
Python -4 Scripting Languages
:Open Source -5
Python -6 NET. Java IronPython, Jython
-7 paradigm Functional Programming, OOP
Python -8 !
Python de facto Perl
Tiobe
Python py. pyc. pyo.
>= .py
>= .pyc
>= .pyo
Downloading/Installing Python
/http://python.org/download
:UNIX/UNIX-Like Python .. Source
Build
./configure
make
make install
README INSTALL
:Windows msi.
) (Interpreter statement
RightClickonMyComputer>Properties (1
AdvancedTab (2
EnvironmentVariables (3
inVariablesfor(UserName):ClickonPATH>Edit (4
;AddC:\Python25 (5
)Chapter3(Basics
variables Loops Conditions
) variable(
.
"" " money
.. IDLE ..
>>>balance=90000 #an integer
>>> print balance
90000
) 100(
>>> balance = balance + 100
>>> print balance
90100
) 890(
>>> balance = balance - 890
>>> balance
89210
List
Lists Enhanced Array
C
30
student_1=Ahmed
student_2=Wael
student_3=Ayman
student_4=Tina
............
student_30=Youssef
30 30 D:
.. List Grouping Data Types
students
]students=[Ahmed, Wael, Ayman, Tina
)>>> type(students
>'<type 'list
list index 0 1 2
idx=n-1
list
]">>>friends=["St0rM", "Squall", "Tina", "Ayman
indexing sequence
>>> friends[0] # 1st
''St0rM
>>> friends[2] # 3rd
''Tina
List List
]">>> students=["Ahmed", "Ayman", "Tina", "Wael
>>> students
]'['Ahmed', 'Ayman', 'Tina', 'Wael
.append(element)
append
>>> students.append("Gina")
>>> students
['Ahmed', 'Ayman', 'Tina', 'Wael', 'Gina']
->>> students += ['Marian']
>>> students
['Ahmed', 'Ayman', 'Tina', 'Wael', 'Gina', 'Marian']
>>> students += ["Omar", "Waleed"]
>>> students
['Ahmed', 'Ayman', 'Tina', 'Wael', 'Gina', 'Marian', 'Omar', 'Waleed']
extend
.extend(iterable)
list iterable
>>> students.extend(["Omar", "Waleed"])
>>> students
['Ahmed', 'Ayman', 'Tina', 'Wael', 'Gina', 'Marian', 'Omar', 'Waleed']
.remove(value)
list value
>>> students.remove("Ayman")
>>> students
['Ahmed', 'Tina', 'Gina', 'Marian', 'Omar', 'Waleed']
)( index
>>> del students[3]
>>> students
['Ahmed', 'Ayman', 'Tina', 'Gina', 'Marian', 'Omar', 'Waleed']
.insert(idx, item)
Ayman insert
(4 ) 3
>>> students.insert(3, "Ayman")
>>> students
['Ahmed', 'Tina', 'Gina', 'Ayman', 'Marian', 'Omar', 'Waleed']
.pop(idx=-1)
idx list +
list
>>> popped=students.pop()
>>> popped
'Waleed'
>>> popped=students.pop(2)
>>> popped
'Tina'
>>> students
['Ahmed', 'Ayman', 'Wael', 'Omar']
.reverse()
>>> students
['Ahmed', 'Ayman', 'Wael', 'Omar']
>>> students.reverse()
>>> students
['Omar', 'Wael', 'Ayman', 'Ahmed']
.sort()
>>> students.sort()
>>> students
['Ahmed', 'Ayman', 'Omar', 'Wael']
.index(value)
>>> students.index("Ayman")
1
.count(value)
list
>>> students.append("Ayman")
>>> students
ListComprehension
ListComprehension
LC - | -
function x
>>>[number*3fornumberinrange(20)]
][0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57
LC ) function (3
20
Prelude>[number*3|number<[1..20]]
][3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60
haskell
) (
>>>[number*3fornumberinrange(20)ifnumber%2==0]
][0, 6, 12, 18, 24, 30, 36, 42, 48, 54
haskell
Prelude>[number*3|number<[1..20],evennumber]
][6,12,18,24,30,36,42,48,54,60
Tuples
1
Tuple - Container - List ..
)
(
)>>> t=(1, 2, 3, 4, 5
>>> t
)(1, 2, 3, 4, 5
>>> t=1, 2, 3, 4, 5
>>> t
)(1, 2, 3, 4, 5
)len(tup
) tup (
>>> t=1, 2, 3, 4, 5
>>>t[0]=9 #Try to set the first element to 9
9
Traceback (most recent call last):
>File "<pyshell#5>", line 1, in <module
t[0]=9 #Try to set the first element to 9
TypeError: 'tuple' object does not support item assignment
Strings
String String
String ) (
string
"!>>> astring="Hello, World
astring Hello, World
" ' ' "
strings
) str (string
)>>> type(astring
>'<type 'str
)len(string
string
)">>> len("Hello, World
12
)(.capitalize
uppercase
)(>>> "hello".capitalize
''Hello
).count(sub
)'>>> "Hello".count('l
2
)(.lower
lowercase
)(>>> "HELlO".lower
''hello
)(.upper
uppercase
)(>>> "helLo".upper
''HELLO
)(.swapcase
)(>>> "hElLo".swapcase
''HeLlO
)(.title
- title-
)(>>> "hello, world".title
''Hello, World
).startswith(sub
)">>> "hello".startswith("he
True
).endswith(sub
)'>>> "hello".endswith('lo
True
: tuple list
list
).find(sub
index
">>> s="Hello, World
)'>>> s.find('W
7
)].strip([chars
chars
)].lstrip([chars
)]rstrip([chars
)(.isalpha
)(.isalnum
)(.isdigit
)(.isupper
uppercase
)(.islower
lowercase
)(.isspace
)(.istitle
title
)(.splitlines
List
string - !mutable -
mutable strings UserString
UserString
:
"somestring="hola
)printsomestring,",",id(somestring
"somestring+="guyZ
hola,3084138464
somestring -- id
+ str class
UserStringModule
Java/C#..etc Stringsareimmutable python
Variable -- Variable -- Concatenation String
>>>s="I'mastring"
>>>s
"I'mastring"
>>>id(s)#getthelocation
13511240
>>>s+=",andyou?"
>>>s
"I'mastring,andyou?"
>>>id(s)#getthelocationnow!
13522272
>>>s="I'mastring,andyou?"
mutablestring
StringBuffer/StringBuilder
-- Module UserStringModule class
PythonPath/Lib/UserString.py
Module
>>> import UserString as us
UserStringmodule alias asus
UserString,MutableString Classes 2 Module
strtype immutable baseclass UserString
mutable UserString subclass MutableString
Mutable hashfunction - - override MutableString :
- - ! unhashable
def__hash__(self):
raiseTypeError,"unhashabletype(itismutable)"
-- ref
>>> ref_m_string=m_string
m_string id ref id
>>>id(ref_m_string)
13511136
>>> m_string += "CRUEL WORLD!"
id
>>>id(m_string)
13511136
ref id
>>>ref_m_string
'Hello,CRUELWORLD!'
>>>id(ref_m_string)
13511136
id immutable Object
>>>im_string=m_string.immutable()#Returnimmutablestring!
>>>im_string
>>>ref_im_string
'Hello,CRUELWORLD!'
>>>id(ref_im_string)
13532856
>>>im_string
'Hello, CRUEL WORLD! blah blah blah'
UserString
Dictionaries
: ) (key, value
}{=>>> d
- - dict
)>>> type(d
>'<type 'dict
'>>> d['Name']='Ahmed
>>> d['Age']=19
'>>> d['Sex']='m
keys 3 ''Name' , Age', 'Sex
)(.keys
Keys
)(>>> d.keys
]'['Age', 'Name', 'Sex
)(.values
Values
).get(key
value key
)'>>> d.get('Name
''Ahmed
None
)'>>> print d.get('Team
None
Indexing
-- Indexing key
>>> d['Name']
'Ahmed'
-- Key
>>> d['Lang']='Ruby'
>>> d['Name']='Youssef'
.pop(key)
value Value Key
.update(d)
d
d.update({'Lang':'Python', 'Singer':'Delta'})
>>> d
{'Lang': 'Python', 'Age': 19, 'Singer': 'Delta', 'Name': 'Youssef'}
.has_key(key)
key
>>> d.has_key('Lang')
True
.items()
key, value tuples list
>>> print d.items()
[('Lang', 'Ruby'), ('Singer', 'Delta'), ('Name', 'Youssef'), ('Country', 'EG'), ('Age', 19), ('Sex',
'm')]
.iteritems()
( ) Iterations
for key, val in d.iteritems():
print key, " => ", val
Lang => Ruby
>>> i=d.iteritems()
>>> i.next()
('Lang', 'Ruby')
>>> i.next()
('Singer', 'Delta')
Conditions
..
" "
if condition then
if_suite
" "
">>> name="ayman
>>> password=147859
>>> if name=="ahmed" and password=="123456":
print "Welcome ahmed" #if_suite
else:
print "Welcome, Who R U?" #else_suite
Welcome, Who R U?
if condition then
if_suite
else_if condition then
else if suite
else_if condition then
else_if suite
else then
else_suite
>>> if name=="ahmed" and password=="123456":
print "Welcome ahmed" #if_suite
elif name=="tina" and password=="36987456":
print "Welcome tina" #elif_suite
elif name=="ayman" and password==147859:
print "Welcome, Ayman" #elif_suite
else:
print "Who R U?"
Welcome, Ayman
if name=="ahmed" and password=="123456":
Escape True
elif name=="tina" and password=="36987456":
Escape True
elif name=="ayman" and password==147859:
True
print "Welcome, Ayman" #elif_suite
:
==
=
if name=="ahmed" and password=="123456":
( = ) and
if name=="ahmed" or name==ayman:
(if = ) or
if not name=="ahmed" :
( = ) not
!=
if name != mahmoud
Loops
while
conditions ..
D:
" "
6
while condition do
while_suite
>>> i=0
>>> while i<10:
print "i: ", i
i += 1
0
1
2
3
4
5
6
7
8
9
I 10 )( - loop
-
print "i: ", i
i:
i:
i:
i:
i:
i:
i:
i:
i:
i:
i += 1
. True loop 10 I I
for
raw_input
print raw_input/input
)raw_input(prompt
prompt
: raw_input,input
input
))eval(raw_input(prompt
)eval(expression
)">>> eval("1+2
3
eval expression
Don'tbreakupwithme
break )
100 (
" hellopython t
t .. t "
"
word="hellopython"
whereist=0
count=0
whilecount<len(word):
ifword[count]=='t':
whereist=count
break
#noneedtokeepgoingon
count += 1
striky@strikydesktop:~/workspace/pytut/src$pythontstbreak.py
Nowcountis1
Nowcountis2
Nowcountis3
Nowcountis4
Nowcountis5
Nowcountis6
Nowcountis7
Ourdancewillcontinue
continue )
(
tstvars=['123mx','hello','acc','9']
forvarintstvars:
ifvar[0].isdigit():
continue#noworkwillbedoneonthisitem,maybethenext?
else:
"print var, " => ", "is valid.
tstvars
for var in tstvars:
) (
tstvar
ifvar[0].isdigit():
?continue #no work will be done on this item, maybe the next
:
3
!AccountSuspended
* raw_input
user_name=Ahmed
user_pass=123456
)Chapter4(Functions&Procedures
DRY:Don'tRepeatYourself
function
def rocks
Python Shell
>>> def rocks():
"!print "Python rocks
)(>>> rocks
!Python rocks
)(>>> rocks
!Python rocks
)(>>> rocks
!Python rocks
Python Perl rocks
function
>>> def rocks():
"!print "Perl rocks
function
) (
>>> def rocks(thing):
"!print thing, "rocks
argument + !rocks
)">>> rocks("Python
!Python rocks
)">>> rocks("Perl
!Perl rocks
function 3+2
>>> def add():
print 2+3
)(>>> add
5
3+2
arguments add function
-1 function
>>> def add(first, second):
print first + second
-2
)>>> add(2, 3
5
)>>> add(3, 7
10
arguments
defprintArgs(first,second,third):
print"First:",first
print"Second:",second
print "Third: ", third
)"printArgs("Hello","Cruel","World
First: Hello
Second: Cruel
Third: World
- arguments - !
)"printArgs(third="World",second="Curel",first="Hello
) ;(
!!
defprintArgs(first="Hello",second="Cruel",third="World"):
print"First:",first
print"Second:",second
print"Third:",third
print""*20
printArgs("Bye")#Changesthefirst..
printArgs(second="")#onlythesecondissetto
)(printArgs
First: Bye
Second: Cruel
Third: World
-------------------First: Hello
Second:
Third: World
-------------------First: Hello
Second: Cruel
Third: World
--------------------
.. - overloading - ) function
function arguments( range
Functions
)>>> val=add(2, 3
5
>>> print val
None
* val !5
expression 5 (add(2, 3 None
print return
* None
None=null=nil=Nothing
Function
return!
>>> def add(first, second):
return first+second
)>>> val=add(2, 3
>>> print val
5
return Function
Functions Procedures
Procedure Function return
- ++/ Function return void Procedure Functions
)raw_input(prompt
)input(prompt
))eval(raw_input(prompt
)eval(expression
expression
)abs(number
- Absolute value -
)>>> abs(10
10
)>>> abs(-10
10
*:
Function getABS argument number abs
)max(iterable
function container - -foreach
)]>>> max([3, 4, 5, 6
6
)">>> max("Ahmed
''m
)min(iterable
max
)">>> min("Ahmed
''A
)]>>> min([3, 4, 5, 6
3
: ASCII ord
chr
)ord(char
)"ord("A
)"ord("a
)chr(65
)chr(97
>>>
65
>>>
97
>>>
''A
>>>
''a
)sum(seq
sequence
)]>>> sum([1, 2, 3, 4, 5
15
* function sum getSum sequence argument
oct(num)
num
>>> oct(15)
'017'
hex(num)
num
>>> hex(15)
'0xf'
len(object)
string argument len
list
>>> len("Ahmed")
5
>>> len([1, 2, 3, 4, 5, 6])
6
D: objects len
round(f_num, digits)
digits f_num function
>>> round(2678.367789)
2678.0
>>> round(2678.367789, 4)
2678.3678
copyright()
>>> copyright()
Copyright (c) 2001-2008 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
>>> credits()
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.
range(end)
1 end 0 list
>>> range(10) #0 to 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start, end)
1 end start List
>>> range(1, 5) #1 to 5
[1, 2, 3, 4]
ASCII function *
To*argsornotto*args
sum
defmysum(alist):
total=0
foriinalist:
total+=i
returntotal
argument list
printmysum([1,2,3,4,5])
- - args*
args
defnewsum(*args):
total=0
foriinargs:
total+=i
return total
arguments :
printnewsum(1,2,3,4,5)
printf
defprintf(fmt,*args):
printfmt%args
printf("Name:%s,Age:%d","Ahmed",20)
#convertedtoprint"Name%s,Age:%d"%("Ahmed",20)
( place holders (%s, %d print args*
- - sprintf * "
To**kwargsornotto**kwargs
- named arguments - keys
defnewprintf(fmt,*args,**kwargs):
print"fmt:",fmt
print"*args:",args
print"**kwargs:",kwargs
#dosomethingusefu
ifkwargs.has_key("verbose"):
print"Verbose..."
newprintf("ThisissomeFMT",1,2,3,4,5,6,verbose=True,cleanup=True,use_ssl=False
Goingglobal
defnewprintf(fmt,*args,**kwargs):
"""Simplefunctiontolearnouthowtouse*,**trickinfunctions."""
print"fmt:",fmt
print"*args:",args
print"**kwargs:",kwargs
#dosomethingusefu
ifkwargs.has_key("verbose"):
print"Verbose..."
( d: ) doc
help __ doc__.
.__doc__
>>>printnewprintf.__doc__#STR
Simplefunctiontolearnouthowtouse*,**trickinfunctions.
Helponfunctionnewprintfinmodule__main__:
help
>>>help(newprintf)
newprintf(fmt,*args,**kwargs)
Simplefunctiontolearnouthowtouse*,**trickinfunctions.
global
__DEBUG=True
defisdebug():
global__DEBUG
return__DEBUG
)(print"Debug?",isdebug
#output:
Debug? True
global global
()globals
__DEBUG=False
defisdebug():
)x,y,z=range(3
)(printlocals
]"returnglobals()["__DEBUG
)(printisdebug
#output:
}#{'y':1,'x':0,'z':2
#False
()locals x,y,z
isdebug
execfile(filepath)
execexpr
Lambda/AnonymousFunctions
lisp lambda
defgetName(name):
returnname
anonyFunc=lambdaname:name
printanonyFunc("Mido")
printgetName("Mido")
#Output:
#Mido
#Mido
defgetSum(*args):
returnsum(args)
anonySum=lambda*args:sum(args)
printgetSum(1,2,3,4,5)
printanonySum(1,2,3,4,5)
#Output:
15
15
map
function
>>> print map(lambda w: w.upper(), ["ahmed", "mostafa", "omar"])
['AHMED', 'MOSTAFA', 'OMAR']
( ) --
lambda
deftoupper(w):
returnw.upper()
users=["ahmed","mostafa","omar"]
printmap(toupper,users)
#output:
#['AHMED', 'MOSTAFA', 'OMAR']
numbers=range(20)
printfilter(lambdai:i&1,numbers)#odds.
printfilter(lambdai:noti&1,numbers)#evens
#output:
#[1,3,5,7,9,11,13,15,17,19]
0 19
n&1 ) (
lambda function
lambda
defisodd(i):
ifi&1:
returnTrue
returnFalse
defiseven(i):
)returnnotisodd(i
printfilter(isodd,numbers)#odds
printfilter(iseven,numbers)#evens
#output:
]#[1,3,5,7,9,11,13,15,17,19
]#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18
2 0 %
? num % 2==0
Iterable
- container -list,tuple,string
Generator
iterator
Iterator
iterable next
- iterable forloop-
>>>lst=range(5)
>>>lst
[0,1,2,3,4]
>>>foriteminlst:
...printitem
...
0
1
2
3
4
>>>s="Hello"
>>>forcharins:
...printchar
...
H
e
l
l
o
>>>iterator=iter(s)
- s-
>>>iterator
<iteratorobjectat0x22e83d0>
>>>iterator.next()
'H'
next
>>>iterator.next()
'e'
>>>iterator.next()
'o'
>>>iterator.next()
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
StopIteration
classStudent(object):
def__init__(self,id,name):
self.id=id
self.name=name
def__str__(self):
return"<Student%d:%s>"%(self.id,self.name)
classStudents(object):
def__init__(self):
self._studentslist=[]
defadd(self,studentobject):
self._studentslist.append(studentobject)
fakedata=[(1,'ahmed'),(2,'khaled'),(3,'ayman'),(4,'tina')]
students=Students()
forid,nameinfakedata:
s=Student(id,name)
students.add(s)
forstudentinStudents:
printstudent
Traceback(mostrecentcalllast):
File"tstiters.py",line27,in<module>
forsinstudents:
TypeError:'Students'objectisnotiterable
printsiter
iterator
printsiter.next()
printsiter.next()
printsiter.next()
printsiter.next()
printsiter.next()
<Student1:ahmed>
<Student2:khaled>
<Student3:ayman>
<Student4:tina>
Traceback(mostrecentcalllast):
File"tstiters.py",line44,in<module>
printsiter.next()
File"tstiters.py",line23,innext
raiseStopIteration
for
forsinstudents:
prints
StopIteration
generators
defifind(self,sname):
forstudentinself._studentslist:
ifstudent.name==sname:
yieldstudent
yield sname self._studentslist
gen=students.ifind('ahmed')#0,4
printgen
printgen.next()
printgen.next()
<generatorobjectifindat0x7f43f1f73af0>
<Student1:ahmed>
<Student5:ahmed>
lazy
iterator generator next
defisearch(string,c):
fori,charinenumerate(string):
ifchar==c:
yieldi
s="HelloWorld!byeworld!"
gen=isearch(s,"o")
printlist(gen)
list yield list
[4,7,18]
next
StopIteration ! list
/http://www.learningpython.com/2009/02/23/iteratorsiterablesandgeneratorsohmy
PythonMagazine
)Chapter5(OOP
OOP X OOP
OOP
Object Oriented Programming
Procedural Programming =
Procedural Programming !
Objects Objects
Fields
fields ) (
-----
Methods
methods ) (
-----
Properties
properties ) Encapsulation( fields
Encapsulation
- -
class
class Human(object):
def __init__(self, name, color, sex, height, weight):
self.name=name
self.color=color
self.sex=sex
self.height=height
self.weight=weight
def eat(self):
#code to eat.
pass
def drink(self):
#code to drink.
pass
def sleep(self):
#code to sleep.
pass
def play(self):
#code to play.
pass
* class class
* class Uppercase
* class ) Object ( object
class object .Object
____init
- Constructor - function ____init
* method .. self self
self .
fields class name, sex, color,.. etc
class
)ahmed=Human("Ahmed", "White", "M", 178,70
-1 object Human class object
-2 print fields
ahmed.name
ahmed.sex
ahmed.height
ahmed.weight
ahmed.color
print
print
print
print
print
10/10 !
ahmed.name=17777777
print ahmed.name
!!!
-1
-2
get/set
fields !
get/set
underscores 2 field
def __init__(self, name, color, sex, height, weight):
self.__name=name
self.__color=color
self.__sex=sex
self.__height=height
self.__weight=weight
self.__weight=new_weight
def set_sex(self, new_sex):
self.__sex=new_sex
fields -1
>>> print ahmed.__name
AttributeError: 'Human' object has no attribute '__name'
error
getters/setters fields -2
ahmed=Human("Ahmed", "White", "M", 178,70)
print ahmed.get_name()
print ahmed.get_color()
ahmed.set_name("Youssef")
print ahmed.get_name()
ahmed.set_name(141241) #Wut?
print ahmed.get_name()
#Output:
Ahmed
White
Youssef
141241
! name set_name
..
str new_name
isinstance
icheck
if type(new_name)==str:
self.__name=new_name
string "
type function isinstance
string new_name ain't a string !
rules ... fields
!encapsulation data members fields attributes
class getters/setters
properties
class Properties
encapsulation fields properties class
getter/setter
ahmed.name=new_name
)ahmed.set_name(new_name
ahmed.name
)(ahmed.get_name
! fields private !
(: properties
property name get_name set_name
)"name=property(fget=get_name, fset=set_name, doc="Gets/Sets the name.
Magicmethods
Magic Methods
__init__ __ method
! len Builtin Functions :
Operator Overloading
__init__ -1
object fields
Constructor ->>> class Human(object):
def __init__(self, name):
#Initialize the fields.
self.name=name
self.hands=2
object
>>> h1=Human("sami")
>>> h1.name
'sami'
>>> h1.hands
2
Inheritance
2- __getitem__(self, key), __setitem__(self, key, val)
MyDict
>>> class MyDict(object):
def __init__(self, d={}):
self.__d=d
def __getitem__(self, key):
if key in self.__d.keys():
return self.__d[key]
def __setitem__(self, key, val):
self.__d[key]=val
self.__d
indexing
__getitem__
>>> md['Name'] #Call __getitem__('Name')
'Ahmed'
__setitem__
>>> md['Name']='Youssef'
>>> md['Name']
'Youssef'
3- .__len__(self)
len
>>> class Lener(object):
def __init__(self, s, alist):
self._s=s
self._list=alist
def __len__(self):
return len(self._s)
len __ len__
self._s
4- .__iter__(self)
for loop iterations generator
>>> class Tech(object):
def __init__(self, langs, nums):
self._langs=langs
self._nums=nums
def __iter__(self):
for lang in self._langs: yield lang
>>> t=Tech(['Python', 'Ruby', 'Rebol'], [1500, 1414, 12515])
>>> for lang in t:
print lang
>>> i=iter(t)
>>> i.next()
'Python'
>>> i.next()
'Ruby'
>>> i.next()
'Rebol'
contatiner :*
5- __str__, __repr__
str, repr
str, repr :
Human readable - - Str
- eval - - repr
-!
>>> class Human(object):
...
def __init__(self, name):
...
self.name=name
...
def __str__(self):
...
return "<Human object: %s>"%self.name
...
def __repr__(self):
...
return "Human('%s')"%self.name
...
>>> h=Human("ahmed")
>>> h
Human('ahmed')
>>> str(h)
'<Human object: ahmed>'
>>> s=repr(h)
>>> s
"Human('ahmed')" #string
>>> res=eval(s)
>>> res
Human('ahmed') # human object!
>>> type(res)
<class '__main__.Human'>
OperatorOverloading
)
(
1+4 Operator+
2*1 * Operator
1-2 Operator
human + human !
Operator
Operator + Strings
Operator + Overloading
.. Operators Operator .
Special Methods Magical Methods
Operator Overloading +
____add
____sub
____mul
class Worker
class Worker(object):
def __init__(self, name, work_hours):
self.name=name
self.work_hours=work_hours
work_hours !
Methods 3
return self.work_hours
def decrement_workinghours(self, hours):
self.work_hours -= hours
return self.work_hours
def mul_workinghours(self, hours):
self.work_hours *= hours
return self.work_hours
* + Operators Overload :
class Worker(object):
def __init__(self, name, work_hours):
self.name=name
self.work_hours=work_hours
def increment_workinghours(self, hours):
self.work_hours += hours
return self.work_hours
def decrement_workinghours(self, hours):
self.work_hours -= hours
return self.work_hours
def mul_workinghours(self, hours):
self.work_hours *= hours
return self.work_hours
def __add__(self, hours):
self.work_hours += hours
return self.work_hours
w Class Object
>>>
>>>
7
>>>
5
>>>
10
w=Worker('EVAN', 4)
w.increment_workinghours(3)
w.decrement_workinghours(2)
w.mul_workinghours(2)
!
w1 Object
>>>
>>>
7
>>>
3
>>>
15
w1=Worker('ANN', 5)
w1+2
w1-4
w1*5
Magic Methods +
+ __add__, __radd__
- __sub__, __rsub__
* __mul__, __rmul__
/ __div__, __rdiv__, __truediv__ (for Python 2.2),
__rtruediv__ (for Python 2.2)
// __floordiv__, __rfloordiv__ (for Python version 2.2)
% __mod__, __rmod__
** __pow__, __rpow__
<< __lshift__, __rlshift__
>> __rshift__, __rrshift__
& __and__, __rand__
BTW,..Enums
setSharedFiles/ query/
Enums
) .. (
) ..(
type
;)TDay=(Saturday=1,Sunday=2,Monday=3,Tuesday=4,Wednesday=5,Thursday=6,Friday=7
(Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday=range(1,7
class MyDays(object): #as rawenum
sunday, monday, tuesday=range(3)
class MyKVDays(object):
sunday, monday, tuesday=0, 9, 2
class
classRawEnum(object):
def__init__(self,start,*enum):#doweneedtosetastart,end,step?veryfancy...
self._kw=dict(zip(enum,range(start,start+len(enum))))
counter=start
forarginenum:#assumingitdoesn'texist.
self.__setattr__(arg,start)
counter+=1
__str__=lambdaself:str(self._kw)#Canbesolvedwithanordereddict.
enum
Colors=RawEnum(5,'white','black','blue')
printColors.white
printColors
kwargs**
classKVEnum(object):
def__init__(self,**kwargs):
self.__kw=kwargs
fork,vinkwargs.items():
self.__setattr__(k,v)
__str__=lambdaself:str(self.__kw)
Days=KVEnum(sunday=0,monday=9,tuesday=2)
printDays
printDays.monday
Chapter6(Inheritance)
Human
class Human(object):
def __init__(self, name, sex):
self._name=name
self._sex=sex
def _set_name(self, name):
self._name=name
def _set_sex(self, sex):
self._sex=sex
name=property(fget=lambda self:self._name, fset=_set_name)
sex=property(fget=lambda self:self._sex, fset=_set_sex)
Employer
class Employer(object):
def __init__(self, name, sex, salary):
self._name=name
self._sex=sex
self._salary=salary
def _set_name(self, name):
self._name=name
def _set_sex(self, sex):
self._sex=sex
def _set_salary(self, salary):
self._salary=salary
name=property(fget=lambda self:self._name, fset=_set_name)
sex=property(fget=lambda self:self._sex, fset=_set_sex)
salary=property(fget=lambda self: self._salary, fset=_set_salary)
class Employer(Human):
def __init__(self, name, sex, salary):
Human.__init__(name, sex)
self._salary=salary
def _set_salary(self, salary):
self._salary=salary
salary=property(fget=lambda self: self._salary, fset=_set_salary)
Human class
classHuman(object):
def__init__(self,name,color,sex):
#Datamembers..
self.__name=name
assertsexinGender.Options#MaleorFemaleonly.
self.__sex=sex
self.__color=color
#getters/setters...
defgetName(self):
returnself.__name
defsetName(self,value):
self.__name=value
defgetSex(self):
returnself.__sex
defsetSex(self,value):
self.__sex=value
defgetColor(self):
returnself.__color
defsetColor(self,value):
self.__color=value
#properties...
name=property(getName,setName,None,"Gets/Setsname.")
sex=property(getSex,setSex,None,"Gets/Setssex.")
color=property(getColor,setColor,None,"Gets/Setscolor.")
__str__=lambdaself:"<Humanobject:%s>"%self.__name
__unicode__=__str__
#methods..
defeat(self):
#Eating
pass
defdrink(self):
#Drinking
pass
defsleep(self):
#Sleeping
pass
eat, drink, sleep
Gender.Options
classGender(object):
Male,Female="Male","Female"#0,1whatever!
Options=(Male,Female)
type
()str casting print magic method __ str__
unicode ) str ___ unicode__
(
def __str__(self):
....
def __unicode__(self):
return self.__str__()
classEmployer(Human):
def__init__(self,name,color,sex,salary,firm):
#Constructthehumanwith(name,color,sex)
Human.__init__(self,name,color,sex)
#Superizeit:)
#super(Employer,self).__init__(name,color,sex)
self.__salary=salary
self.__firm=firm
defgetFirm(self):
returnself.__firm
defsetFirm(self,value):
self.__firm=value
firm=property(getFirm,setFirm,None,"Gets/Setsthefirm.")
defgetSalary(self):
returnself.__salary
defsetSalary(self,value):
self.__salary=value
salary=property(getSalary,setSalary,None,"Gets/Setssalary.")
__str__=lambdaself:"<Employerobject:(%s,%d)>"%(self.getName(),self.salary)
#super(Employer,self)
defeat(self):
print"Thisismybreak(eatorhavingfunhummm?"
defsleep(self):
print "Hi, it's me sleeping!"
( ) Human Human
) (
overriden Human )(
classManager(Employer):
def__init__(self,name,color,sex,salary,firm):
#Employer.__init__(self,name,color,sex,salary,firm)
super(Manager,self).__init__(name,color,sex,salary,firm)
#printself.__dict__
#{'_Human__color':'white','_Employer__salary':200000,'_Human__name':'Wael',
'_Employer__firm':'Sun','_Human__sex':'Male'}
defraiseSalaryOf(self,emp,theraise):
assert(isinstance(emp,Employer)andemp.firm==self.firm)
emp.salary += theraise
dictionary __ dict__.
if__name__=="__main__":
ahmed=Employer("ahmed","white",Gender.Male,50000,"Google")
omar=Employer("omar","black",Gender.Male,40000,"Sun")
tina=Employer("christina","white",Gender.Female,50000,"Google")
emps=(ahmed,omar,tina)
wael=Manager("Wael","white",Gender.Male,200000,"Sun")
wael.raiseSalaryOf(omar,9000)
)printissubclass(Employer,Human
printisinstance(ahmed,Human)#AhmedisaHuman..
printHuman.__bases__#inheritsobject.
print Manager.__bases__ #Inherits Employer..
(issubclass(C, B C B
(isinstance(object, Type object Type
__ __bases ) (
assert ? assert
assert
? ASSERT assert
statement ) (
Exceptions, Errors
MultipleInheritance
:
classWolf(object):
def__init__(self):
self.__bite=True
can_bite=lambdaself:self.__bite
deffullmoon(self):
print"Wooooooooooooooooooooooooo"
defbite(self,h):
print"I'mcursed"
classWerewolf(Human,Wolf):
def__init__(self,name,color,sex):
Human.__init__(self,name,color,sex)
Wolf.__init__(self)
yasser=Werewolf("yasser","black",Gender.Male)
printyasser.__dict__
print"Canbite?",yasser.can_bite()
yasser.bite(ahmed)
printWerewolf.__bases__
classWolf(object):
def__init__(self):
self.__bite=True
can_bite=lambdaself:self.__bite
deffullmoon(self):
print"Wooooooooooooooooooooooooo"
defbite(self,h):
print"I'mcursed"
classWerewolf(Human,Wolf):
def__init__(self,name,color,sex):
Human.__init__(self,name,color,sex)
Wolf.__init__(self)
Werewolf wolf
yasser=Werewolf("yasser","black",Gender.Male)
printyasser.__dict__
print"Canbite?",yasser.can_bite()
yasser.bite(ahmed)
print Werewolf.__bases__
{'_Human__color':'black','_Wolf__bite':True,'_Human__name':'yasser','_Human__sex':'Male'}
Canbite?True
I'mcursed
(<class'__main__.Human'>,<class'__main__.Wolf'>)
(<class '__main__.Human'>, <class '__main__.Wolf'>)
__bases__
- - MRO
/http://www.python.org/download/releases/2.3/mro
)Chapter7(Exceptions,Errors
!
SyntaxError
software writing software rewriting text editor
text writer P:
exceptions " "
4 ) (
try
except
finally
raise
1234-
try exception
:except exception
: finally exception
) (
:raise exceptions
>>> 1/0
Traceback (most recent call last):
>File "<pyshell#0>", line 1, in <module
1/0
ZeroDivisionError: integer division or modulo by zero
>>>
try:
print 1/0
except ZeroDivisionError, e:
print e.message
>>> def sayHi(name):
if not isinstance(name, str):
raise ValueError("name ain't string.")
else:
print "Hi, %s"%name
exception
return
IntOnly Exception raise
Error Exception -1
IntOnly raise -2
>>> def readInt():
inp=raw_input("Enter a num: ")
try:
i=int(inp) #cast to integer.
return i
except Exception:
raise IntOnly("Integers only are allowed.")
-3
>>> try:
j=readInt()
except IntOnly, e:
print e.message
try block j readInt
e.message ( e ) IntOnly )(
except
finally
#!/usr/bin/python
f=None#outoftryblock.Asfinallydoesn'thavetry'context
try:
f=file('somefile,'r')
lines=f.readlines()
forlineinlines:
printline,#avoid\n\n!
exceptIOError,e:
print'IOErrorError'
finally:#cleaningup
iff:
f.close()
try:
suite
except EX1, ex1: suite
except EX2, ex2: suite
except EX3, ex3: suite
finally: suite
/
:BaseException
:Exception
:ImportError
:KeyboardInterrupt ) ^(C
:NameError identifier
:SyntaxError
:IndexError sequence
:KeyError
:IOError IO
:OverflowError
:OSError
:AssertionError assert expression
>>> 1==0
False
>>> assert 1==0
Traceback (most recent call last):
>File "<pyshell#2>", line 1, in <module
assert 1==0
AssertionError
)Chapter8(IO
BasicIO
files IO Input/Output
filetype )
(file
fileobject open fileclass
open fileobject
)open(name,mode,buffering
name
mode ) ( r
r
) ) w
a
r+
w+
modes b binary binaryread,binarywrite,..etc
buffering buffering ) 1-
(
)(.close
fileobject
).read(num=None
)(.readline
)(.readlines
) (list
)(.tell
).fseek(offset,whence=0
offset whence
whence ) 0 ( ) 1 ( ) 2 (
iotest.xcd 0123456789
).write(s
s
).writelines(seq_of_strings
seq_of_strings
- write sequence)(.fileno
FileDescriptor file
)(.flush
buffer
.name
.mode
accessmode
.encoding
.closed
FNAME="iotest.xcd"
txt="""
line1
line2
line3
line4
line5
line6
line7
sometext
yadayadayada!
"""
f=open(FNAME,"w")
printf.fileno()
printf.name
printf.mode
printf.closed
f.write(txt)
f.close()
print f.closed
txt iotext.xcd
3
iotest.xcd
w
False
True
f=open(FNAME,"r")
lines=f.readlines()
forlineinlines:
print "LINE = > ", line, #avoid printing a new line.
LINE
LINE
LINE
LINE
LINE
LINE
LINE
LINE
LINE
LINE
=
=
=
=
=
=
=
=
=
=
>
>
>
>
>
>
>
>
>
>
line
line
line
line
line
line
line
some
yada
1
2
3
4
5
6
7
text
yada yada!
sys.argv argumentvector
intmain(intargc,char**argv){
}
myecho.py
#!bin/python
fromsysimportargv#argumentsvector.
print"Numberofarguments:",len(argv)
forarginargv:
print arg
os,os.path
os,os.path modules 2
importos
importos.pathasop
os.uname(...)
(sysname, nodename, release, version, machine) tuple
>>>printos.uname()
('Linux', 'striky-desktop', '2.6.24-21-generic', '#1 SMP Tue Oct 21
23:43:45 UTC 2008', 'i686')
os.getcwd()
>>>printos.getcwd()
/home/striky/workspace/pytut/src
os.getcwdu()
unicode
os.environ
HOME,LOGNAME,PATH,..etc environment dictionary
forkey,valinos.environ.items():
printkey,"=>",val
os.getenv(key, default)
environ
print os.getenv("HOME")
default
root
def isroot():
return os.getenv("USER")=="root"
os.chdir(to)
to cwd
print os.getcwd()
os.chdir("/home/striky")
print os.getcwd()
os.chdir("Music")
print os.getcwd()
#output
/home/striky/workspace/pytut/src
/home/striky
/media/s3/Music
>>>p=os.getcwd()#/home/striky/workspace/pytut/src
>>>printos.listdir(p)
['userstringtest.py', 'iosess.py', 'gcombo.py', 'iohelpers.py',
'oopsample.py', 'iotest.xcd', 'gtk1.py', 'complpath.py']
os.link(src,dest)
dest src hard link
os.symlink(src, dest)
dest src symbolic link
os.unlink(path)
path
os.remove(path)
os.unlink
os.rmdir(path)
os.rename(src, dest)
os.removedirs(path)
os.removedirs('foo/bar/baz')
foo bar baz
chmod(path, mode)
path mode
chown(path, uid, gid)
path uid, gid
print os.sep # /
/home/striky
print os.curdir #.
."
print os.altsep#None
print os.pardir#..
.."
print os.extsep#.
."
print os.pathsep#:
: PATH
print repr(os.linesep)#\n
n\"
p=os.getcwd()#/home/striky/workspace/pytut/src
F=p+r'/'+"iohelpers.py"
printop.basename(F)
printop.isfile(F)
printop.islink(F)
printop.isabs(F)
printop.isdir(F)
printop.isdir(p)
printop.ismount("/media/s3")
printop.abspath(F)
printop.dirname(F)
printop.split(F)
printop.splitdrive(F)
printop.splitext(F)
printop.exists(F+"xx")#Nope!
printop.getatime(F)#lastaccesstime
printop.getmtime(F)#lastmodificationtime
printop.getsize(F)#filesize.
printop.join("/home","striky","Music")
iohelpers.py
True
False
True
False
True
True
/home/striky/workspace/pytut/src/iohelpers.py
/home/striky/workspace/pytut/src
('/home/striky/workspace/pytut/src', 'iohelpers.py')
('', '/home/striky/workspace/pytut/src/iohelpers.py')
False
1226557143.0
1226557142.0
521
/home/striky/Music
('/home/striky/workspace/pytut/src/iohelpers', '.py')
exists(path)
isfile(path)
path
isdir(path)
islink(path)
path
link path
ismount(path)
isabs(path)
basename(path)
abspath(path)
dirname(path)
getatime(path)
lastaccess
getmtime(path)
lastmodification
getctime(path)
windows lastcreation lastchange
getsize(path)
path
join(a)
path
split(path)
basename dirname tuple
splitdrive(path)
,drive tuple
splitext(path)
tuple
expanduser(path)
)~( tilde
expanduser("~/Desktop")
'/home/ahmed/Desktop'
FilePointer
FileHandler.write
>>>F = open(fileName, 'w')
>>>print >> F, 'Hola'
opened
>>>F.close()
>>>F=open(fileName, 'r')
>>>for line in F.readlines(): print line
Hola
'w'permission File
>>> f = open('C:\\2.txt', 'w') #Open 2.txt for writing mode.
>>> print >> f, 'Hola!'
#Add 'Hola' to it
- Appendmode File ..
>>> print >> f, ' so great' # added to the line 'File pointers are'
>>> f.close()
)Chapter9(Modules/Packages:ChargingaBattery
batteriesincluded syntax
modules modules package
)>>> cos(30
Traceback (most recent call last):
>File "<stdin>", line 1, in <module
NameError: name 'cos' is not defined
module "
cos
modules
..
ImportingaModule:
module math
import
import math
module ImportError
>>>try:
...importmymath
...exceptImportError,e:
...printe
...
No module named mymath
magicalimport
)'>>> msys=__import__('sys
as ) ( msys
sys
>>> import sys as mysys
FindingNemo
ImportError ) sitepackages
(
sys.path
>>>importsys
>>>sys.path
['','/usr/lib/python2.5/sitepackages/Tempita0.2py2.5.egg','/usr/lib/python2.5/sitepackages/Mako0.2.2
py2.5.egg',
....
]....
FirstModule
##################################################
#Author:AhmedYoussef
#License:GPLV3
#Module:firstmodule
#Purpose:Learningmodules
#Date:12202008
###################################################
firstmodule.py
defaloha():
print"Aloha!"
defadios():
"!print "Adios
modules
greeter.py aloha,adios firstmodule.py
importfirstmodule
firstmodule.aloha()
)(firstmodule.adios
striky@strikydesktop:~/workspace/pytut/src$pythongreeter.py
Aloha!
!Adios
usingfrom
fromfirstmoduleimportaloha,adios
aloha()
)(adios
module
* from somemodule import
*
Reloading
module reload module
defadios():
print"Adios!"
)(aloha
greeter.py
striky@strikydesktop:~/workspace/pytut/src$pythongreeter.py
Aloha!
Aloha!
!Adios
aloha firstmodule
module
modules __ __name module "____main
firstmodule
if__name__=="__main__":
#Testing...
aloha()
Packages
modules
modules oracle,sqlite,mysql
databases
import databases.mysql
fromdatabasesimportmysql
myfirstpackage/
|__init__.py
|mysql.py
|oracle.py
`-- sqlite.py
4 myfirstpackage
__ init__ -1
mysql.py,oracle.py,sqlite.py 3 -2
mysql.py
defabout():
print "mysql module."
oracle.py
defabout():
print "oracle module."
sqlite.py
defabout():
print "sqlite module."
__init__
print"__init__myfirstpackage"
import mysql
VERSION="1.42.0"
striky@strikydesktop:~/workspace/pytut/src$pythondbtester.py
__init__myfirstpackage
['VERSION','__builtins__','__doc__','__file__','__name__','__path__','mysql']
1.42.0
mysqlmodule.
Traceback(mostrecentcalllast):
File"dbtester.py",line6,in<module>
myfirstpackage.sqlite.about()
AttributeError: 'module' object has no attribute 'sqlite'
sqlite AttributeError
import myfirstpackage.sqlite
Platform
)
(
platform
striky@strikydesktop:~/workspace/pytut/src$pythonplatformreport.py
[architecture=>('32bit','ELF')]
[dist=>('debian','lenny/sid','')]
[java_ver=>('','',('','',''),('','',''))]
[libc_ver=>('glibc','2.4')]
[mac_ver=>('',('','',''),'')]
[machine=>i686]
[node=>strikydesktop]
[platform=>Linux2.6.279generici686withdebianlennysid]
[processor=>]
[python_build=>('r252:60911','Oct5200819:24:49')]
[python_compiler=>GCC4.3.2]
[python_version=>2.5.2]
[python_version_tuple=>['2','5','2']]
[release=>2.6.279generic]
[system=>Linux]
[uname=>('Linux','strikydesktop','2.6.279generic','#1SMPThuNov2021:57:00UTC2008','i686','')]
[version=>#1SMPThuNov2021:57:00UTC2008]
[win32_ver=>('','','','')]
function
platform.dist()
platform.machine()
platform.uname()
importplatform
forsindir(platform):
ifnots.startswith("_"):#Ifitdoesnotstartwithanunderscore.
f=getattr(platform,s)#Fetchtheattribute(shouldbeafunction..)
try:
print"[%s=>%s]"%(s,f())#Printsattr,returnedvalue
except:
pass #Global catch for functions requires params(e.g popen).
)Chapter10(Databases
Python/MySQL
MySQLDocumentation
apilevel
DBAPI 2.0
-1 import MySQLdb
>>> import MySQLdb as ms
- ms alias >>>ms.apilevel
''2.0
>>>ms.threadsafety
1
threadsafety
][3 ,0
:0
threads module
:1
threads module connections
-2
threads module connections ) cursors (
-3
module,connections cursors
paramstyle
queries
) ( s% 1: 2: ) ( format
>>>ms.paramstyle
''format
)(1close
)(2commit
transaction ) transactions autocommit
(
)(3rollback
transaction ) commit
rollback!(
4cursor()
5set_sql_mode(sqlmode)
( MySQLdocumentation ) sqlmode
6set_character_set(charset)
characterset
( ) cursor
2 CursorObjects
SQL * *
SQLstatements cursor statements
rows
methods fields Cursor
execute(sqlQuery,args)
args SqlStatement
latebinding
wherename=?
wherename=:name
rowcount
callproc(proc,args)
!storedprocedure
fetchone()
fetchmany()
( cursor ) arraysize
arraysize
fetchmanymethod
fetchall()
rownumber
!cursor index
(backend MySQL )
CREATETABLE`users`(
`id`int(11)NOTNULLauto_increment,
`username`varchar(50)NOTNULL,
`password`varchar(50)NOTNULL,
`state`tinyint(2)NOTNULL,
PRIMARYKEY(`id`),
UNIQUEKEY`username`(`username`)
);
Python/MySQL crud
Create/Read/Updata/Delete
MySQLdb -1
import MySQLdb as ms
DBMan -2
classDBMan(object):
def__init__(self,dbname="pyim"):
self._dbname=dbname
self._sqlconnection=ms.connect(host="localhost",
user="root",
passwd="",
db="pyim")
self._sqlcursor=self._sqlconnection.cursor()
defdeleteUser(self,username):
sqlstmt="DELETEFROMusersWHEREusername='%s'"%username
try:
self._sqlcursor.execute(sqlstmt)
self._sqlconnection.commit()#commit
exceptException,e:
print e.message
deflogin(self,username,pwd):
md5edpass=self._md5(pwd)
sqlstmt="SELECTusername,passwordFROMusersWHEREusername='%s'ANDpassword='%s'"%
(username,md5edpass)
self._sqlcursor.execute(sqlstmt)
ifself._sqlcursor.fetchone():
self.setState(State.Online, username)
defsetState(self,state,username):
sqlstmt="UPDATEusersSETstate=%dWHEREusername='%s'"%(state,username)
try:
self._sqlcursor.execute(sqlstmt)
exceptException,e:
print e.message
defgetAllUsers(self):
sqlstmt="SELECTusername,stateFROMusers"
self._sqlcursor.execute(sqlstmt)
forrowinself._sqlcursor.fetchall():
yieldrow[0],row[1]
DBAPI MySQLdb :
DBAPI3
Refs:
MySQLdb1.2.2docs
PythonDBAPISpecificationsv2
PySQLite
PySQLite
Python SQLite interface
Lib
pythonsetup.pyinstall
module import -1
dbapi2 submodule lib pysqlite2 import PySQLite
- file db DB Connection -2
dbapi2 connectmethod Connection - file
#!bin/python
from pysqlite2 import dbapi2 as SQLite
connection
Memory QuickAccessDB :
memConnection=SQLite.connect(:memory:)
DB Cursor Connection
cursor=dbConnection.cursor() #gets a cursor object..
name:varchar(50)
phone:varchar(10)
SQLStatement
sqlStmt='CREATE TABLE info (id INTEGER PRIMARY KEY, name VARCHAR(50), phone
VARCHAR(10))'
>>>cursor.execute(sqlStmt)
<pysqlite2.dbapi2.Cursorobjectat0x0128B230
>
>>>cursor.execute('INSERTINTOinfoVALUES(null,"ahmedyoussef","12345678")')
<pysqlite2.dbapi2.Cursorobjectat0x0128B230>
>>>cursor.execute('INSERTINTOinfoVALUES(null,"3amermohamed","41234114")')
<pysqlite2.dbapi2.Cursor object at 0x0128B230>
.. fields
>>>username="guru"
>>> phone ="36987452"
.. Commitmethod
>>> dbConnection.commit()
:
connection connect
autocommit=1
rollbackmethod
cursor,connection
cursor.close()
dbConnection.close();
connection db connect
connectionobject cursor cursorobject
sqlstatements
connection
>>> dbConnection=SQLite.connect("mydb.sqlite") #reopen the db..
cursor
>>>cursor=dbConnection.cursor()
>>> #let's query the db..
sqlstatement
sqlStmt
>>> cursor.execute(sqlStmt)
result iterate
>>>forrowincursor:
#id,name,phone
print""
print"ID:",row[0]
print"Name:",row[1]
print"Phone:",row[2]
ID:1
Name:ahmedyoussef
Phone:12345678
ID:2
Name:3amermohamed
Phone:41234114
ID:3
Name:guru
Phone: 36987452
iterator next.
>>>cursor.next()
(1,u'ahmedyoussef',u'12345678')
>>>cursor.next()
(2,u'3amermohamed',u'41234114')
fetchmany(num)
>>>ret=cursor.fetchmany(2)
>>>ret
[(1,u'ahmedyoussef',u'12345678'),(2,u'3amermohamed',u'41234114')]
fetchone()
>>>one=cursor.fetchone()
>>>one
(3, u'guru', u'36987452')
userdefinedtype ..
class
classPerson(object):
def__init__(self,name,phone):
self.name=name
self.phone=phone
.. Person declaredtypes parse database cursor connection
memory
#createaconnection.
memConnection=SQLite.connect(':memory:',detect_types=SQLite.PARSE_DECLTYPES)
#cursor
cursor=memConnection.cursor()
SQLite ..
SQLite.register_adapter(Person,adaptPerson)
SQLite.register_converter("person", convToPerson)
p1=Person("ahmed","12345678")
p2=Person("rul3z", "89745632")
cursor.execute('INSERTINTOtestVALUES(null,?)',(p1,))
cursor.execute('INSERT INTO test VALUES(null, ?)', (p2, ))
#select..
cursor.execute('SELECT*fromtest')
forrowincursor:
printrow
#output:
(1,(ahmed;12345678))
(2, (rul3z;89745632))
cursor,connection
#cleanup
cursor.close()
memConnection.close()
#!bin/python
frompysqlite2importdbapi2asSQLite
#dbName='myobjDBTest.sqlite'
#createaconnection.
#dbConnection=SQLite.connect(dbName,detect_types=SQLite.PARSE_DECLTYPES)
memConnection=SQLite.connect(':memory:',detect_types=SQLite.PARSE_DECLTYPES)
#cursor
cursor=memConnection.cursor()
classPerson(object):
def__init__(self,name,phone):
self.name=name
self.phone=phone
def__repr__(self):
return"(%s;%s)"%(self.name,self.phone)
#defineamethodtoregisterit..
defadaptPerson(person):
return"%s;%s"%(person.name,person.phone)
defconvToPerson(text):
name,phone=map(str,text.split(";"))
returnPerson(name,phone)
SQLite.register_adapter(Person,adaptPerson)
SQLite.register_converter("person",convToPerson)
p1=Person("ahmed","12345678")
p2=Person("rul3z","89745632")
#createatesttable..
cursor.execute("CREATETABLEtest(idINTEGERPRIMARYKEY,pperson)")
#add
cursor.execute('INSERTINTOtestVALUES(null,?)',(p1,))
cursor.execute('INSERTINTOtestVALUES(null,?)',(p2,))
#select..
cursor.execute('SELECT*fromtest')
forrowincursor:
printrow
#cleanup
cursor.close()
memConnection.close()
:
http://www.devshed.com/c/a/Python/Us...iteinPython/
http://www.initd.org/tracker/pysqlite/wiki/basicintro
http://www.initd.org/pub/software/py...inedfunctions
sqlite3 :
ORMs
Storm
canonical ORM storm
>>> from storm.locals import *
>>>classBook(object):
...__storm_table__="book"
...id=Int(primary=True)
...name=Unicode()
...
npages=Int()
>>> db=create_database("sqlite:")
( )
>>> store=Store(db)
>>> store.execute("CREATE TABLE book (id INTEGER PRIMARY KEY, name VARCHAR,
npages INTEGER)")
>>>rbook.name=u"IntroductiontoRuby"
>>>rbook.npages=210
>>>printrbook.id,rbook.name,rbook.npages
None Introduction to Ruby 210
>>>store.add(rbook)
<__main__.Bookobjectat0xb78aecac>
>>>printrbook.id,rbook.name,rbook.npages
NoneIntroductiontoRuby210
>>>
>>>pybook.name=u"PyGuide"
>>>pybook.npages=230
>>>printpybook
<__main__.Bookobjectat0xb78ae80c>
>>>store.add(pybook)
<__main__.Book object at 0xb78ae80c>
>>>pythonbook=store.find(Book,Book.name==u"PyGuide").one()
>>>pythonbook.name
u'PyGuide'
one
primarykey
>>>store.get(Book,1).name
'u'Introduction to Ruby
flush flush
>>>store.flush()
>>>store.get(Book,1).id
1
>>>pythonbook=store.find(Book,Book.name==u"PyGuide").one()
>>>pythonbook.id
2
commit
SQL
/https://storm.canonical.com
SQLObject
ORMs SQLObject storm
-1 sqlobject
>>>fromsqlobjectimport*
>>>
>>>sqlhub.processConnection=connectionForURI('sqlite:/:memory:')
>>>
-3
>>>classBook(SQLObject):
...title=StringCol()
...
npages=IntCol()
-4
>>>Book.createTable()
[]
Book -5
>>>rbbook=Book(title="IntroductiontoRuby",npages=230)
>>>rbbook.title
'IntroductiontoRuby'
>>>rbbook.npages
230
>>>rbbook
<Book1title="'Introductionto...'"npages=230>
>>>pybook="PyGuide"
>>>pybook=Book(title="PyGuide,npages=330")
>>>pybook=Book(title="PyGuide",npages=330)
>>>pybook
<Book 2 title='PyGuide' npages=330>
get id
>>>Book.get(1)
<Book1title="'Introductionto...'"npages=230>
>>>book=Book.get(2)
>>>book
<Book 2 title='PyGuide' npages=330>
select
>>>books=Book.select()
>>>list(books)
[<Book 1 title="'Introduction to ...'" npages=230>, <Book 2 title='PyGuide'
npages=330>]
Book
>>>rbbooks=Book.select(Book.q.title=="IntroductiontoRuby")
>>>list(rbbooks)
[<Book 1 title="'Introduction to ...'" npages=230>]
230 select selectBy
>>>pybook
<Book2title='PyGuide'npages=330>
>>>pybook.npages=230
>>>pages230=Book.selectBy(npages=230)
>>>list(pages230)
[<Book 1 title="'Introduction to ...'" npages=230>, <Book 2 title='PyGuide'
npages=230>]
/http://www.sqlobject.org
SQLAlchemy
TODO
)Chapter11(ParsingData
XMLingwithPython
xml ..
Markups
http://docs.python.org/lib/markup.html
XML
<?xmlversion="1.0"?>
<!DOCTYPEbooksSYSTEM"books.dtd">
<?xmlstylesheettype="text/xsl"href="books.xsl"?>
<books>
<bookid="1">
<name>IntroductiontoPython</name>
<author>AhmedYoussef</author>
<price>80</price>
</book>
<bookid="2">
<name>IntroductiontoJava</name>
<author>WaelMuhammed</author>
<price>130</price>
</book>
<bookid="3">
<name>IntroductiontoRuby</name>
<author>AhmedYoussef</author>
<price>70</price>
</book>
<bookid="4">
<name>IntroductiontoLinuxProgramming</name>
<author>AhmedMostafa</author>
<price>90</price>
</book>
</books>
bookstag root
book
id book attributes booktag
name,author,pricetags book
1minidom
minidom DOM implementation
import xml.dom.minidom as md #(parse, parseString..)
parse,parseString
file parse
string parseString
documentobject
nodeobject
/ xml
nodeType
textnode,element,comment,document,..etc
parentNode
None attrs ( documentroot )
previousSibling
node node
nextSibling
node node
childNodes
node nodes
hasChildNodes()
nodes
firstChild
lastChild
hasAttributes()
attributes
appendChild(child)
insertBefore(child,befored)
befored child
removeChild(child)
child
normalize()
textnodes
/ documentobject
documentElement#usedasaproperty
books rootelement
getElementsByTagName(tagName)#tagName
elementobject tagName
createElement(tagName)
tag
createComment(comment)
createAttribute(attr)
attribute
nsURI namespace NS
.
ElementObject
tagName#usedasaproperty
element
getElementsByTagName*
documentobject
hasAttribute(attrName)
attribute
getAttribute(attrName)
attrName attribute
setAttribute(attrName,val)
val attrName attribute
removeAttribute(attrName)
minidom -1
import xml.dom.minidom as md #(parse, parseString..)
ifbook.hasAttribute("id"):#idanditshouldhaveone!
print"ID:",book.getAttribute("id")
forchildinbook.childNodes:
ifchild.nodeType==child.ELEMENT_NODE:
ifchild.tagName=="name":
child.normalize()
print "Book: ",child.firstChild.data
globalvariable - - doc
global doc
ifchild.tagName=="name":
child.normalize()
print"Book:",child.firstChild.data
element,comment,text,..etc nodes
string data nametag textnode firstChild
<name>textnode...</name
defgetTotalSum():
globaldoc
thesum=0
prices=doc.getElementsByTagName("price")
forpriceinprices:
price.normalize()
thesum+=int(price.firstChild.data)#TOint.
return thesum
priceelements
<price>numeric_value</price>
thesum int
inspectBooks()
print"TotalSum:",getTotalSum()
#output
RootElement:books
ID:1
Book:IntroductiontoPython
ID:2
Book:IntroductiontoJava
ID:3
Book:IntroductiontoRuby
ID:4
Book:IntroductiontoLinuxProgramming
Total Sum: 370
2SAX
events content
-1
fromxml.saximportmake_parser,parseString
fromxml.sax.handlerimportContentHandler
ContentHandler eventhandlers
)(startDocument
)(endDocument
)startElement(name,attrs
el
><el[attr1=val1,attr2=val2,...attrN=valN]>CONTENT</el
)characters(content
><el[attr1=val1,attr2=val2,...attrN=valN]>CONTENT</el
)endElement(el
el
><el[attr1=val1,attr2=val2,...attrN=valN]>CONTENT</el
NS namespace
Attributes mapping dictionary
)(getLength
)(getNames
attribute
)(getType
CDATA
)getValue(attrName
attribute attrName
-1 /
fromxml.saximportmake_parser,parseString
from xml.sax.handler import ContentHandler
make_parser XMLreader
parseString xml string
parse XMLreaderobject ) parse,parseString
(minidom
( )ContentHandler
string xml -2
xmldoc="""<?xmlversion="1.0"?>
<books>
<bookid="1">
<name>IntroductiontoPython</name>
<author>AhmedYoussef</author>
<price>80</price>
</book>
<bookid="2">
<name>IntroductiontoJava</name>
<author>WaelMuhammed</author>
<price>130</price>
</book>
<bookid="3">
<name>IntroductiontoRuby</name>
<author>AhmedYoussef</author>
<price>70</price>
</book>
<bookid="4">
<name>IntroductiontoLinuxProgramming</name>
<author>AhmedMostafa</author>
<price>90</price>
</book>
</books>
"""
ContentHandler -3
class BooksHandler(ContentHandler):
.. -ContentHandler - override
def__init__(self):
self._total=0#Sumofprices.
self._curel=None
self._curid=None
self._booksInfo=[]
self._authors=[]
self._total
self._curel
id self._curid
name,id self._booksInfo
self._authors
defgetTotal(self):
returnself._total
defgetBooksInfo(self):
returnself._booksInfo
defgetAuthors(self):
return self._authors
getters
lambda properties
booksinfo=property(fget=lambdaself:self._booksInfo)
authors=property(fget=lambdaself:self._authors)
total=property(fget=lambdaself:self._total)
defstartDocument(self):
#print"StartingDocument."
pass
defendDocument(self):
#print"EndingDocument."
pass
defstartElement(self,el,attrs):
#print"Starting",el
self._curel=el
ifel=="book":
#gettheid..
self._curid=attrs.getValue("id") #attrs["id"]
el attrs
-1 self._curel
self._curel=el
-2 book attribute id id
reader
ifel=="book":
#gettheid..
]"self._curid=attrs.getValue("id") #attrs["id
dict getValue.
defcharacters(self,content):
ifcontent.strip():
ifself._curel=="price":
#print"InPrice.."
try:
self._total+=int(content)
except:
pass
elifself._curel=="name":
self._booksInfo+=[(content,self._curid)]
elifself._curel=="author":
self._authors+=[content]
else:
pass
-4 BooksHandler
)(bh = BooksHandler
p.setContentHandler(bh)
))"p.parse(open("books2.xml
)parseString(xmldoc, bh
http://docs.python.org/lib/modulexml.sax.html
/http://www.saxproject.org
DOM tree !
SAX events
3Expatundercover
ContentHandler -2
classParsingHandler(object):
def__init__(self,xml):
self._curel=None
self._curattrs=None
self._inbook=False
self._books=[]
self._thesum=0
self._p=exp.ParserCreate()
self._p.StartElementHandler=self.__startElement
self._p.EndElementHandler=self.__endElement
self._p.CharacterDataHandler=self.__charsDataHandler
self._p.Parse(xml)
booktag
parser
ParserCreate XMLParserTypeobject -1
handlers handlers -2
Parsemethod xml -3
getters
defgetTotalSum(self):
returnself._thesum
defgetBooksInfo(self):
returnself._books
defprintBooksInfo(self):
forbookinself._books:
printbook
self._pparser handlers
def__startElement(self,el,attrs):
print"Starting:",el,attrs
ifel=="book":
self._inbook=True
self._curel=el
self._curattrs=attrs
def__charsDataHandler(self,data):
ifdata.strip():
ifself._inbookandself._curel=="name":
self._books+=[data]
elifself._curel=="price":
self._thesum+=int(data)
else:
pass
def__endElement(self,el):
ifel=="book":
self._inbook=False
self._curel, self._curattrs=None,None
if__name__=="__main__":
p=ParsingHandler(xmldoc)
print"Totalsum:",p.getTotalSum()
p.printBooksInfo()
xml string xmldoc
Totalsum:370
IntroductiontoPython
IntroductiontoJava
IntroductiontoRuby
Introduction to Linux Programming
HappyMapper
<?xml version="1.0"?>
<computer>
<library>
<books>
<book id="1">
<name>Introduction to Python</name>
<author>Ahmed Youssef</author>
<price>80</price>
</book>
<book id="2">
<name>Introduction to Java</name>
<author>Wael Muhammed</author>
<price>130</price>
</book>
<book id="3">
<name>Introduction to Ruby</name>
<author>Ahmed Youssef</author>
<price>70</price>
</book>
<book id="4">
<name>Introduction to Linux Programming</name>
<author>Ahmed Mostafa</author>
<price>90</price>
</book>
</books>
</library>
</computer>
.. DOM,SAX
forbookincomputer.library.books:
printbook.id,book.name,",by",book.author
totalsum=sum([int(str(book.price))forbookincomputer.library.books])
print"SUM:",totalsum
1 Introduction
2 Introduction
3 Introduction
4 Introduction
SUM: 370
to
to
to
to
- - attributes
amazon
<?xmlversion="1.0"encoding="UTF8"?>
<ItemSearchResponsexmlns="http://webservices.amazon.com/AWSECommerceService/200510
05">
<OperationRequest>
<HTTPHeaders>
<HeaderName="UserAgent">
</Header>
</HTTPHeaders>
<RequestId>16WRJBVEM155Q026KCV1</RequestId>
<Arguments>
<ArgumentName="SearchIndex"Value="Books"></Argument>
<ArgumentName="Service"Value="AWSECommerceService"></Argument>
<ArgumentName="Title"Value="RubyonRails"></Argument>
<ArgumentName="Operation"Value="ItemSearch"></Argument>
<ArgumentName="AWSAccessKeyId"Value="dontbeaswoosh"></Argument>
</Arguments>
<RequestProcessingTime>0.064924955368042</RequestProcessingTime>
</OperationRequest>
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<SearchIndex>Books</SearchIndex>
<Title>RubyonRails</Title>
</ItemSearchRequest>
</Request>
<TotalResults>22</TotalResults>
<TotalPages>3</TotalPages>
<Item>
<ASIN>0321480791</ASIN>
<DetailPageURL>http://www.amazon.com/gp/redirect.html%3FASIN=0321480791%26tag=ws
%26lcode=xm2%26cID=2025%26ccmID=165953%26location=/o/ASIN/0321480791%253FSubscript
ionId=dontbeaswoosh</DetailPageURL>
<ItemAttributes>
<Author>MichaelHartl</Author>
<Author>AureliusProchazka</Author>
<Manufacturer>AddisonWesleyProfessional</Manufacturer>
<ProductGroup>Book</ProductGroup>
<Title>RailsSpace:BuildingaSocialNetworkingWebsitewithRubyonRails(Addison
WesleyProfessionalRubySeries)</Title>
</ItemAttributes>
</Item>
</Items>
</ItemSearchResponse>
printrt.OperationRequest.HTTPHeaders.Header.Name
printrt.OperationRequest.Arguments[0].Name
printrt.OperationRequest.RequestProcessingTime
printrt.Items.TotalPages
printrt.Items.TotalResults
printrt.Items.Item.ASIN
print rt.Items.Item.DetailPageURL
UserAgent
SearchIndex
0.064924955368042
3
22
0321480791
http://www.amazon.com/gp/redirect.html%3FASIN=0321480791%26tag=ws
%26lcode=xm2%26cID=2025%26ccmID=165953%26location=/o/ASIN/0321480791%253FS
ubscriptionId=dontbeaswoosh
Twitter
<source>web</source>
<truncated>false</truncated>
<in_reply_to_status_id>1234</in_reply_to_status_id>
<in_reply_to_user_id>12345</in_reply_to_user_id>
<favorited></favorited>
<user>
<id>4243</id>
<name>John Nunemaker</name>
<screen_name>jnunemaker</screen_name>
<location>Mishawaka, IN, US</location>
<description>Loves his wife, ruby, notre dame football and iu
basketball</description>
<profile_image_url>http://s3.amazonaws.com/twitter_production/profile_imag
es/53781608/Photo_75_normal.jpg</profile_image_url>
<url>http://addictedtonew.com</url>
<protected>false</protected>
<followers_count>486</followers_count>
</user>
</status>
</statuses>
user
statuses.status.user.inspect_me()
Attrs:
Tags:
id => 4243
name => John Nunemaker
screen_name => jnunemaker
location => Mishawaka, IN, US
description => Loves his wife, ruby, notre dame football and iu
basketball
profile_image_url =>
http://s3.amazonaws.com/twitter_production/profile_images/53781608/Photo_7
5_normal.jpg
url => http://addictedtonew.com
protected => false
followers_count => 486
happymapper -1
import happymapper
ElementTree
TODO
HTMLingwithPython
--
#!/usr/bin/envpython
#*coding:utf8*
fromHTMLParserimportHTMLParserasHP
importurllib2asulib
importsys
deffetchdatafrom(url):
returnulib.urlopen(url).read()
defas_unicode(data):
returndata.decode("cp1256").encode("utf8")
classPageParser(HP):
def__init__(self):
self._ina=False
self._links=[]
links=lambdaself:self._links
defhandle_start_tag(self,tag,attrs):
pass
defhandle_data(self,data):
pass
defhandle_endtag(self,tag):
pass
defgetlinks(url):
htmlsrc=fetchdatafrom(url)
p=PageParser()
p.feed(htmlsrc)
return p.links()
SAX
HTML handle_endtag handle_data handle_starttag
fetchdatafrom string
as_unciode cp1256 ) unicode dataj
(
PageParser HTMLParser
ContentHandler
feed
getlinks links
BeautifulSoup
HTML/XMLparser
HTML BeautifulSoup XML
BeautifulStoneSoup
BeautifulSoup
#!bin/python
importBeautifulSoupasbs
importurllib2asulib
deffetchdatafrom(url):
"returnulib.urlopen(url).read()or"\n
defgetzetcodemain():
)'returnfetchdatafrom('http://zetcode.com
))(soup=bs.BeautifulSoup(getzetcodemain
forelinsoup.findAll('a'):
#[0][0]ishref.
)print"[url=%s]%s[/url]"%(el.attrs[0][1],el.contents
http://www.crummy.com/software/BeautifulSoup/documentation.html
ParsingCSVFiles
CSV commaseparatedvalues
) (comma ) (
/
ahmed,19,m
ayman,20,m
) (
name,age,sex
ahmed,19,m
ayman,20,m
somefile.csv
ahmed, m, 19
wael, m, 20
radwa, f, 19
gina, f, 21
ayman, m, 20
csvmodule
importcsv
reader object "
()cvs.reader
reader=csv.reader(open("somefile.csv", "rb")) #default dialect. #b as a catch for win32.
forrowinreader:
printrow,"at:",reader.line_num
importcsv
)"f=open("somefile.csv","rb
try:
reader=csv.reader(f)#defaultdialect.#basacatchforwin32.
forrowinreader:
printrow,"at:",reader.line_num
exceptException,ex:
printex.message
finally:
f.close()
reader=csv.DictReader(f,fieldnames=("name","age","sex"))#defaultdialect.#basacatchfor
win32.
forrowinreader:
printrow,"at:",reader.line_num
importcsv
f=open("somefile1.csv","w")
try:
writer=csv.writer(f)
inputrows=(
(1,"ahmed","ahmedf1@gmail.com"),
(2,"ayman","aymanf2@gmail.com"),
(3,"smsm","smsm@yahoo.com")
)
headers=("id","user","email")
writer.writerow(headers)
forrowininputrows:
writer.writerow(row)
exceptException,ex:
printex.message
finally:
)(f.close
CSV
ConfigParser
! ini. ConfigParser
ini.
[program]
name = SVM
version = 0.2.4
license = GPLv3
[author]
name = Ahmed Youssef
email = guru.python@gmail.com
fromConfigParserimport*
-2
cp=SafeConfigParser()#createanobjectofSafeConfigParser
RawConfigParser RawConfigParser,ConfigParser,SafeConfigParser
SafeConfigParser ConfigParser
-3
cp.read("tst.cfg") #read by filename.
readmethod cp configparserobject
.add_section(section)
.set(section,key,value)
value section key
.sections()
.has_section(section)
section
.get(section,key)
section key
.options(section)
section options
.has_option(section,option)
SECTCRE=re.compile(
r'\['#[
r'(?P<header>[^]]+)'#verypermissive!
r'\]'#]
)
OPTCRE=re.compile(
r'(?P<option>[^:=\s][^:=]*)'#verypermissive!
r'\s*(?P<vi>[:=])\s*'#anynumberofspace/tab,
#followedbyseparator
#(either:or=),followed
#byany#space/tab
r'(?P<value>.*)$'#everythinguptoeol
)
ConfigParser.py
Regex:
TODO
sys.argv list
#echo.py
fromsysimportargv
print"ARGV:",argv
fori,arginenumerate(argv):
)print "Argv[%d]: %s"%(i, arg
argv
striky@strikydesktop:~/workspace/pytut/src$pythonecho.pyHello
ARGV:['echo.py','Hello']
Argv[0]:echo.py
Argv[1]:Hello
striky@strikydesktop:~/workspace/pytut/src$pythonecho.py"HelloWorld"
ARGV:['echo.py','HelloWorld']
Argv[0]:echo.py
Argv[1]:HelloWorld
enumerate
(argv list )container ) ( index
Gimmeusage!
usage
usage
defusage():
"""Myfancyusagehelper"""
........
defconsoleMain():
iflen(argv)!=DEFINED_LENGTH:
GIMME_USAGE
if__name__=="__main__":
consoleMain()
GIMMEoptparser!
striky@striky-desktop:~$ python mufhrs.py -f http://linuxac.org/forum/forumdisplay.php?
f=23 -l 1 -u 3 -s 1 -t vb > pgfihrsx2.txt
)
( SMF
s
1
u
3
t
vb
step=1
upper=3
ftype=vb
!!
( optparse )
defconsoleMain():
optsparser=OptionParser()
optsparser.add_option("f","forum",dest="forumlink",help="ForumSection")
optsparser.add_option("l","lower",dest="lower",help="Lowestpage")
optsparser.add_option("u","upper",dest="upper",help="Upperpage")
optsparser.add_option("s","step",dest="step",help="Step")
optsparser.add_option("t","type",dest="ftype",help="Forumtype(e.g)vb")
options,args=optsparser.parse_args()#defaultedtosys.argv[1:]
#printoptions,"====",args
forumlink=optsparser.values.forumlink
lower=int(optsparser.values.lower)
upper=int(optsparser.values.upper)
forumtype=optsparser.values.ftype.lower()
step=int(optsparser.values.step)
OptionParser optparse -1
from optparse import OptionParser
OptionParser -2
optsparser=OptionParser()
add_option
f-
forum- )(
forumlink
option
-3
-1
-2
-3
-4
optsparser.add_option("f","forum",dest="forumlink",help="ForumSection")
optsparser.add_option("l","lower",dest="lower",help="Lowestpage")
optsparser.add_option("u","upper",dest="upper",help="Upperpage")
optsparser.add_option("s","step",dest="step",help="Step")
optsparser.add_option("t","type",dest="ftype",help="Forumtype(e.g)vb")
help
Options:
h,helpshowthishelpmessageandexit
fFORUMLINK,forum=FORUMLINK
ForumSection
lLOWER,lower=LOWER
Lowestpage
uUPPER,upper=UPPER
Upperpage
sSTEP,step=STEPStep
tFTYPE,type=FTYPE
Forumtype(e.g)vb
striky@strikydesktop:~/workspace/pytut/src$pythonmufhrs.pyhelp
Usage:mufhrs.py[options]
Options:
h,helpshowthishelpmessageandexit
fFORUMLINK,forum=FORUMLINK
ForumSection
lLOWER,lower=LOWER
Lowestpage
uUPPER,upper=UPPER
Upperpage
sSTEP,step=STEPStep
tFTYPE,type=FTYPE
Forum type (e.g) vb
forumlink=optsparser.values.forumlink
lower=int(optsparser.values.lower)
upper=int(optsparser.values.upper)
forumtype=optsparser.values.ftype.lower()
step=int(optsparser.values.step)
(: setattr :
:
stdin, stdout, stderr cat *
sys
os.system
) exitstatus os system
(
exitstatus.py
#!/usr/bin/envpython
#*coding:utf8*
defwho():
name=raw_input("Name:")
ifname!="Ahmed":
print"NotAhmed"
exit(1)
else:
print"Welcome"
who()
striky@strikydesktop:~/workspace/pytut/src$pythonexitstatus.py
Name:Ahmed
Welcome
striky@strikydesktop:~/workspace/pytut/src$echo$?
0
exitcode ? $
:
Exceptions --
subprocess
cat
( system ) subprocess
>>>importsubprocessassb
>>>ret=sb.call(['cat','exitstatus.py'])
#!/usr/bin/envpython
#*coding:utf8*
defwho():
name=raw_input("Name:")
ifname!="Ahmed":
print"NotAhmed"
exit(1)
else:
print"Welcome"
who()
>>>ret
0
list call
>>>catoutput=sb.Popen(["cat","exitstatus.py"],stdout=sb.PIPE).communicate()[0]
>>>printcatoutput
#!/usr/bin/envpython
#*coding:utf8*
defwho():
name=raw_input("Name:")
ifname!="Ahmed":
print"NotAhmed"
exit(1)
else:
print"Welcome"
who()
communicate tuple
) (
Popen args
stdout,stdin,stderr None ) PIPE
(pipe fileobject filedescriptor
shell ) True False ) excevp
( (
Replacer
-1 dict
-2 ) recursion (
#!bin/python
#Imports#
importos
importos.pathasop
importtime
fromsysimportargv
classReplacer(object):
def__init__(self,parentDir,dic={},exts=[]):
self.__parentDir=parentDir
self.__dic=dic
self.__exts=exts
self.__replacingTimes=0
def__getExt(self,s):
#idx=s.rfind(".")
#ext=s[idx:]
#returnext
returnop.splitext(s)[1]
defreplace(self):
start=self.__parentDir
foreinos.listdir(start):#foreachentryinos.listdir..
path=start+op.sep+e
ifos.path.isfile(path):
ext=self.__getExt(path)
ifnotextinself.__exts:
continue#ReLoop..
#replace..
f=file(path,"r")
src=f.read()
f.close()
forkeyinself.__dic:
self.__replacingTimes+=src.count(key)
src=src.replace(key,self.__dic[key])
f=file(path,"w")
f.write(src)
f.close()
elifos.path.isdir(path):
#RECURSE..
rep=Replacer(path,self.__dic,self.__exts)
rep.replace()
else:
continue
def__init__(self,parentDir,dic={},exts=[]):
self.__parentDir=parentDir
self.__dic=dic
self.__exts=exts
self.__replacingTimes=0
parentDir
os.path.splitext
def__getExt(self,s):
#idx=s.rfind(".")
#ext=s[idx:]
#returnext
returnop.splitext(s)[1]
- ." rfind
h1.ext1.ext2
replace
defreplace(self):
start=self.__parentDir
foreinos.listdir(start):#foreachentryinos.listdir..
path=start+op.sep+e
ifos.path.isfile(path):
ext=self.__getExt(path)
ifnotextinself.__exts:
continue#ReLoop..
#replace..
f=file(path,"r")
src=f.read()
f.close()
forkeyinself.__dic:
self.__replacingTimes+=src.count(key)
src=src.replace(key,self.__dic[key])
f=file(path,"w")
f.write(src)
f.close()
elifos.path.isdir(path):
#RECURSE..
rep=Replacer(path,self.__dic,self.__exts)
rep.replace()
else:
continue
-1
foreinos.listdir(start):#foreachentryinos.listdir..
path=start+op.sep+e
-2
ifos.path.isfile(path):
ext=self.__getExt(path)
) ( -3
continue
ifnotextinself.__exts:
continue #Re-Loop..
-5
#replace..
f=file(path,"r")
#Note:NotreadinglinebylineasI'venevermetamorethan1MBtextfile!
src=f.read()
f.close()
forkeyinself.__dic:
self.__replacingTimes+=src.count(key)
src=src.replace(key, self.__dic[key])
-6
f=file(path,"w")
f.write(src)
f.close()
) -7
recursion replace
elifos.path.isdir(path):
#RECURSE..
rep=Replacer(path,self.__dic,self.__exts)
rep.replace()
else:
continue
defconsoleMain():
##pythonreplacer.pyroot[old][new][exts]
root,oldones,newones,exts=argv[1:5]
oldones=oldones.split(",")#usecommainbetween.
newones=newones.split(",")#usecommainbetween.
exts=exts.split(",")
#usecommainbetween.
iflen(oldones)==len(newones):
dic=dict(zip(oldones,newones))
#print"DIC:",dic
#print"EXTS:",exts
start=time.time()
rep=Replacer(root,dic,exts)
rep.replace()
end=time.time()
print"Time:",(endstart)
else:
print"len(keys)!=len(values)"
exit(1)
start=time.time()
rep=Replacer(root,{old:new},[exts])
rep.replace()
end=time.time()
print "Time: ", (end-start)
optparse
os.walk
forroot,dirs,filesinos.walk(self.__parentDir):
forfinfiles:
if("*"orself.__getExt(f))inself.__exts:
fullpath=op.join(root,f)
..
..
Chapter12(Networking)
sockets
http://en.wikipedia.org/wiki/Internet_socket
SimpleServer
#simpleserver.py
import socket
class EchoServer(object):
def __init__(self, host='', port=51002):
self._host, self._port=host, port
self._endpoint=(host, port) #host, addr
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start(self):
self.sock.bind(self._endpoint)
self.sock.listen(1)
print "Server running on: ", self._port
self.handle_request()
def handle_request(self):
while True: #Waits for a client.
clientsock, addr=self.sock.accept()
#clientfile=clientsock.makefile('rw', 0) #Create a file-like object.
print "Connection from: ", addr
clientsock.sendall(str(addr)+" you are connected to server...")
while True: #communication loop
#clientfile.write("Got: "+msg+"\n")
#Cleaning UP
#clientfile.close()
clientsock.close()
if __name__=="__main__":
try:
es=EchoServer()
es.start()
except KeyboardInterrupt:
exit()
EchoServer
class EchoServer(object):
def __init__(self, host='', port=51002):
self._host, self._port=host, port
self._endpoint=(host, port) #host, addr
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
( ) endpoint -1
TCP Socket -2
SO_REUSEADDR -3
start
def start(self):
self.sock.bind(self._endpoint)
self.sock.listen(1)
print "Server running on: ", self._port
self.handle_request()
( endpoint ) bind -1
listen tcp listener -2
handle_request -3
def handle_request(self):
socket accept
socket file-like object makefile
sendall
(bufsize ) recv
SimpleClient
#simpleclient.py
import socket
class SimpleClient(object):
def __init__(self, endpoint=('127.0.0.1', 51002)):
self._endpoint=endpoint
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(self._endpoint)
def start(self):
while True:
data=self.sock.recv(8096)
if not data:
break
print data
msg=raw_input("> ")
if not msg:
break
self.sock.send(msg)
self.sock.close()
if __name__=="__main__":
try:
sc=SimpleClient()
sc.start()
except KeyboardInterrupt:
exit()
SimpleClient
class SimpleClient(object):
def __init__(self, endpoint=('127.0.0.1', 51002)):
self._endpoint=endpoint
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(self._endpoint)
connect ( endpoint )
start
def start(self):
while True:
data=self.sock.recv(8096)
if not data:
break
print data
msg=raw_input("> ")
if not msg:
break
self.sock.send(msg)
self.sock.close()
SocketServer
TCPServer
) UDPServer
(
#!/usr/bin/envpython
#*coding:utf8*
fromSocketServerimportTCPServer,StreamRequestHandler
classMyStreamRequestHandler(StreamRequestHandler):
defhandle(self):
print"Gotconnectionfrom:",self.client_address
self.wfile.write(str(self.client_address)+"youareconnectedtoserver.")
#Communicationloop...
whileTrue:
msg=self.request.recv(1024)
ifnotmsg:
break
print">>",msg
#Senditback...
self.request.send(msg)
print"Donehandling..."
defgo(endpoint=('',52002)):
addr=endpoint
tcpServer=TCPServer(addr,MyStreamRequestHandler)
tcpServer.allow_reuse_address=1
print"Serverstarted..."
tcpServer.serve_forever()#inf.loop
if__name__=="__main__":
try:
go()
exceptKeyboardInterrupt:
exit()
import socket
class SimpleClient(object):
def __init__(self, endpoint=('127.0.0.1', 52002)):
self._endpoint=endpoint
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(self._endpoint)
def start(self):
#self.sock.sendall("Hey you!!")
while True:
data=self.sock.recv(1024)
if not data:
break
print data
msg=raw_input("> ")
if not msg:
break
self.sock.sendall(msg)
#self.sock.close()
if __name__=="__main__":
try:
sc=SimpleClient()
sc.start()
except KeyboardInterrupt:
exit()
MixIns
Forking Threading
SocketServer module ForkingMixIn ThreadingMixIn
class MyServer(ThreadingMixIn,TCPServer):
!pass #Done
class MyServer(ForkingMixIn, TCPServer):
!pass #Done
Forking - - Threading
)
(
#!bin/python
importsocket
importthreading
classChatServer(object):
'''Indexer...'''
def__init__(self,port):
self.port=port
addr=('',self.port)
self._bufsize=2048
self.listener=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#Quickrestarts.
self.listener.bind(addr)
self.alSocks=[]
#self.tListening=threading.Thread(target=self.listeningHandler,args=[])
#self.tListening.start()
self.listeningHandler()#Startlistening...
deflisteningHandler(self):
self.listener.listen(5)
print"Serverstarted.."
whileTrue:
clientSocket,clientAddr=self.listener.accept()
#Handletheclientinanewthread...
self.tHandleClient=threading.Thread(target=self.clientHandler,args=[clientSocket])
self.tHandleClient.start()
defclientHandler(self,clientSocket):
self.alSocks+=[clientSocket]
print"connectionfrom:",clientSocket.getpeername()
self._bufsize=2048
try:
whileTrue:
data=clientSocket.recv(self._bufsize)
ifnotdata:
break
#handlesendingallrecievedinanotherthread..
#serverToAll=threading.Thread(target=self.serverToAll,args=[clientSocket,data])
#serverToAll.start()
self.serverToAll(clientSocket,data)
exceptException:
#don'tact
printclientSocket.getpeername(),"closed..."
finally:
self.alSocks.remove(clientSocket)
clientSocket.close()
defserverToAll(self,currentClient,data):
try:
forsockinself.alSocks:
ifnotsock==currentClient:
sock.send(data)
else:
pass
exceptException,e:
printe
if__name__=="__main__":
chatServer=ChatServer(8030)
threading.Thread
list args target
( args)
#!bin/python
importsocket
importthreading
classPeer(object):
def__init__(self,serverAddr=('localhost',8030),alias="anonymouse"):
self.serverAddr=serverAddr
self.tcpClient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.alias=alias
self._bufsize=2048
self.tcpClient.connect(self.serverAddr)
print"\nConnectedtoserver.."
#self.tClientToServer=threading.Thread(target=self.clientToServerHandler,args=[])
#self.tClientToServer.start()
self.clientToServerHandler()
defclientToServerHandler(self):
print"StartChattin'\n"
whileTrue:
data=raw_input()
msg=alias+":"+data
ifnotdata:
break
serverToClient=threading.Thread(target=self.serverToClientHandler,args=[])
serverToClient.start()
#self.serverToClientHandler()
self.tcpClient.send(msg)
defserverToClientHandler(self):
whileTrue:
data=self.tcpClient.recv(self._bufsize)
ifnotdata:
break
printdata
if__name__=="__main__":
alias=raw_input("Alias:")
peer=Peer(alias=alias)
AppwithaBUG
classPeerInfo(object):
def__init__(self,alias,sharedFiles,listeningPort):
self.alias=alias
self.sharedFiles=sharedFiles
self.listeningPort=listeningPort
def__str__(self):
sb="Alias:"+self.alias
sb+="\nFiles:"+str(self.sharedFiles)
sb+="\nListensAt:"+str(self.listeningPort)
returnsb
defserialize(obj):
'''Serializeanobjecttoastring...'''
returnmarshal.dumps(obj)
defdeserialize(objString):
'''Deserializeanobjectstring...'''
returnmarshal.loads(objString)
if__name__=="__main__":
p=PeerInfo("ahmed",[1,2,3,4],80)
printp
print"alias:",p.alias
print"files:",p.sharedFiles
print"port:",p.listeningPort
peerInfoclass class
alias,sharedFiles,ListeningPort
methods 2 Objects
serialize deserialize
DiscoveryServer
-1 Connect Alias,SharedFiles,ListeningPort
-2 Clients
-3 Client
-4 Clients
-5 SharedFiles
-6
-7 Client
................... -8
}{'clientIP:port':peerInfoObject
(self.listener=socket.socket(socket.AF_INET,socket.SOCK_STREAM
(self.listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1
Class .. port ..
: register/ client
: setSharedFiles/ share
: setNick/ Nick alias
: showall/
: query/
class DiscoveryServer(object):
'''Indexer...'''
def __init__(self, port, maxPeers=5):
self.port=port
addr=('', self.port)
self.maxPeers=maxPeers
self.supportedCommands=["/register", "/setNick", "/setSharedFiles",
"/showall", "/query"]
self.listener=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
self.listener.bind(addr)
self.tListening=threading.Thread(target=self.listeningHandler,
args=[])
self.tListening.start()
self.alSocks=[]
# {clientAddr:peerInfo Object}
self.db={}
self.log=[]
self.BUF=2048
.. .. log
" " Sockets List self.alSocks
self.tListening=threading.Thread(target=self.listeningHandler, args=[])
deflisteningHandler(self):
self.listener.listen(self.maxPeers)
print"ServerStarted..."
whileTrue:
clientSocket,clientAddr=self.listener.accept()
print"Gottaaconnectionfrom",clientAddr
tClientHandling=threading.Thread(target=self.clientHandler,args=[clientSocket])
tClientHandling.start()
clientSocket.close()
listening
thread Connect connect client foreverloop
clientHandler method
tClientHandling=threading.Thread(target=self.clientHandler,
args=[clientSocket])
clientSocket,clientAddress tuple return acceptmethod
defclientHandler(self,clientSocket):
self.alSocks+=[clientSocket]
formatedAddress=clientSocket.getpeername()[0]+":"+str(clientSocket.getpeername()[1])
objString=""
try:
whileTrue:
objString=clientSocket.recv(self.BUF)
ifnotobjString:
break
data=deserialize(objString)
#printdata
tAnalyzeData=threading.Thread(target=self.analyzeData,args=[data,clientSocket])
tAnalyzeData.start()
objString=""
exceptException,e:
print"E:",e
printclientSocket.getpeername(),"closed.."
self.alSocks.remove(clientSocket)
delself.db[formatedAddress]
ClientSocket Client method
Client thread serverclass alSockslist
parsing method thread data
clientSocket data argument method
tAnalyzeData=threading.Thread(target=self.analyzeData,args=[data,clientSocket])
tAnalyzeData.start()
analyzeDatamethod ..
except Exception,e :
print "Error: ", e
except Exception, e:
print "Data: ", data
print "Error: ", e
)self.alSocks.remove(clientSocket
tuple
)(register,files=[],listeningPort/
peerInfoobject
command query
Server
)( Client alSocks active
alSocks Clients
.. "
"super
showallTomethod
Queryingfiles
+ method socket
def queryFile(self, fileName, clientSocket):
print "Querying: ", fileName
data=""
for addr, pInfo in self.db.items():
if fileName in pInfo.sharedFiles:
data += "\n"+addr + " | " + pInfo.alias + " => " +
fileName
data += "\n\t" + pInfo.alias + " Listens at: "+
str(pInfo.listeningPort)
print data
clientSocket.send(serialize(data))
Indexer DiscoveryServer
Peer Client
peers Peers Server Peer
internalserver client
fetching
Constructor
alias -1
listofsharedFiles -2
endPoint -3
ServerIP+port endPoint
thread server connection
def__init__(self,alias,serverAddr=(),sharedFiles=[]):
self.alias=alias
self.serverAddr=serverAddr
self.sharedFiles=sharedFiles
self.tcpClient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.tcpClient.connect(self.serverAddr)
self.BUF=1024
self.listeningPort=rnd.randint(8081,10000)
self.pInfo=PeerInfo(self.alias,self.sharedFiles,self.listeningPort)
print"\nConnectedtoserver..."
self.tClientToServer=threading.Thread(target=self.clientToServerHandler,args=[])
self.tClientToServer.start()
serverobject files fetch Peers
thread
#listenforconnectionsinbackground..
self.addr=('',self.listeningPort)
self.listener=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.listener.bind(self.addr)
self.tListening=threading.Thread(target=self.listeningHandler,args=[])
self.tListening.start()
port set
randintmethod .. Peers
Discovery 1024 randomint randommodule
Server
self.listeningPort=rnd.randint(8081,10000)
registerAtServerMethod
defregisterAtServer(self):
msg=("/register",self.alias,self.sharedFiles,self.listeningPort)
self.tcpClient.send(serialize(msg))
connect
defclientToServerHandler(self):
print"StartChatting.."
#firstregisterthefiles...
self.registerAtServer()
whileTrue:
tServerToClient=threading.Thread(target=self.serverToClientHandler,args=[])
tServerToClient.start()
data=raw_input()
ifnotdata:continue
ifdata.lower=="exit":exit()
ifdata.split("")[0]=="/fetch":
fileneeded=data.split("")[1]
addr=data.split("")[2]
tFetchFile=threading.Thread(target=self.fetchFile,args=[addr,fileneeded])
tFetchFile.start()
else:
msg=self.alias+":"+data
self.tcpClient.send(serialize([msg]))
defserverToClientHandler(self):
whileTrue:
data=deserialize(self.tcpClient.recv(self.BUF))
ifnotdata:break
ifisinstance(data,list):#data['tina:hi']
printdata[0]
else:
printdata
fetching
deffetchFile(self,addr,fileneeded):
#addrisformated=>addr:listeningPort
endPoint=addr.split(":")[0],int(addr.split(":")[1])
fetchTCPClient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
fetchTCPClient.connect(endPoint)
fetchTCPClient.sendall(serialize(("/fetch",fileneeded)))
tDownloadFile=threading.Thread(target=self.downloadFile,args=[fetchTCPClient,fileneeded])
tDownloadFile.start()
defdownloadFile(self,fetchTCPClient,fileneeded):
f=file(fileneeded,"wb")
whileTrue:
try:
buf=fetchTCPClient.recv(self.BUF)
ifnotbuf:
break
f.write(buf)
exceptEOFError,eofErr:
print"EOFError:",eofErr
exceptException,e:
print"Error:",e
break
print"FileDownloaded!"
f.close()
fetchTCPClient.close()
clients ..
listening thread already -
self.tListening=threading.Thread(target=self.listeningHandler,args=[])
self.tListening.start()
deflisteningHandler(self):
self.listener.listen(5)
whileTrue:
clientSocket,clientAddr=self.listener.accept()
tClientHandling=threading.Thread(target=self.clientHandler,args=[clientSocket])
tClientHandling.start()
Multithreaded
internalserver connect client thread
defclientHandler(self,clientSocket):
rcvd=clientSocket.recv(self.BUF)
data=deserialize(rcvd)
ifisinstance(data,tuple):
ifdata[0]=="/fetch":#goon..
fileneeded=data[1]#(/fetch,fileneeded,from)
print"FileRequest:",fileneeded
f=file(fileneeded,"rb")
whileTrue:
try:
buf=f.read(self.BUF)
ifnotbuf:
break
clientSocket.send(buf)
exceptException,e:
print"Error:",e
break
f.close()
clientSocket.close()
print"Copied!"
if __name__=="__main__":
alias=raw_input("Alias: ")
sharedFiles=os.listdir(os.getcwd())
peer=Peer(alias, ('localhost', 8080), sharedFiles)
DiscoveryServer
Code:
#!bin/python
importsocket
importsys
importos
importthreading
fromutilsimportserialize,deserialize,PeerInfo
classNotSupportedCommand(Exception):
pass
classDiscoveryServer(object):
'''Indexer...'''
def__init__(self,port,maxPeers=5):
self.port=port
addr=('',self.port)
self.maxPeers=maxPeers
self.supportedCommands=["/register","/setNick","/setSharedFiles","/showall","/query"]
self.listener=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.listener.bind(addr)
self.tListening=threading.Thread(target=self.listeningHandler,args=[])
self.tListening.start()
self.alSocks=[]
#{clientAddr:peerInfoObject}
self.db={}
self.log=[]
self.BUF=2048
deflisteningHandler(self):
self.listener.listen(self.maxPeers)
print"ServerStarted..."
whileTrue:
clientSocket,clientAddr=self.listener.accept()
print"Gottaaconnectionfrom",clientAddr
tClientHandling=threading.Thread(target=self.clientHandler,args=[clientSocket])
tClientHandling.start()
clientSocket.close()
defclientHandler(self,clientSocket):
self.alSocks+=[clientSocket]
formatedAddress=clientSocket.getpeername()[0]+":"+str(clientSocket.getpeername()[1])
objString=""
try:
whileTrue:
objString=clientSocket.recv(self.BUF)
ifnotobjString:
break
data=deserialize(objString)
#printdata
tAnalyzeData=threading.Thread(target=self.analyzeData,args=[data,clientSocket])
tAnalyzeData.start()
objString=""
exceptException,e:
print"E:",e
printclientSocket.getpeername(),"closed.."
self.alSocks.remove(clientSocket)
delself.db[formatedAddress]
defanalyzeData(self,data,clientSocket):
formatedAddress=clientSocket.getpeername()[0]+":"+str(clientSocket.getpeername()[1])
try:
ifisinstance(data,tuple):#registering...
pInfo=PeerInfo(data[1],data[2],data[3])#(register,alias,files,port)
print"Registering:",pInfo.alias
printpInfo
self.db[formatedAddress]=pInfo#peerInfoobject..
printself.db
ifisinstance(data,list):
try:
#splitthesender'salias..
#recvd=['tina:/showall']
recvd=data[0].split(":")[1]
cmd=recvd.split("")[0]
#testcmd...
ifnotcmdinself.supportedCommands:
self.sendToAll(data,clientSocket)
else:
ifcmd=="/showall":
self.showAllTo(clientSocket)
ifcmd=="/query":
fileName=recvd.split("")[1]
self.queryFile(fileName,clientSocket)
ifcmd=="/setNick":
self.setNick(formatedAddress,recvd.split("")[1])
exceptException,e:
print"Error:",e
exceptException,e:
print"Data:",data
print"Error:",e
self.alSocks.remove(clientSocket)
defqueryFile(self,fileName,clientSocket):
print"Querying:",fileName
data=""
foraddr,pInfoinself.db.items():
iffileNameinpInfo.sharedFiles:
data+="\n"+addr+"|"+pInfo.alias+"=>"+fileName
data+="\n\t"+pInfo.alias+"Listensat:"+str(pInfo.listeningPort)
printdata
clientSocket.send(serialize(data))
defshowAllTo(self,clientSocket):
data="\n\nOnlineUsers:\n"
foraddr,pInfoinself.db.items():
data+=pInfo.alias+">"+addr+"\n"
data+="\n\n"
printdata
clientSocket.send(serialize(data))
defsendToAll(self,msg,clientEx):
print"MessageRecieved:",msg
try:
forsockinself.alSocks:
ifnotsock==clientEx:
sock.send(serialize(msg))
else:
pass
exceptException,e:
print"Error:",e
defsetNick(self,to,newNick):
self.db[to].alias=newNick
print"NickChanged..."
printself.db[to]
if__name__=="__main__":
discoveryServer=DiscoveryServer(8080)
Utils:
importmarshal
classPeerInfo(object):
def__init__(self,alias,sharedFiles,listeningPort):
self.alias=alias
self.sharedFiles=sharedFiles
self.listeningPort=listeningPort
def__str__(self):
sb="Alias:"+self.alias
sb+="\nFiles:"+str(self.sharedFiles)
sb+="\nListensAt:"+str(self.listeningPort)
returnsb
defserialize(obj):
'''Serializeanobjecttoastring...'''
returnmarshal.dumps(obj)
defdeserialize(objString):
'''Deserializeanobjectstring...'''
returnmarshal.loads(objString)
if__name__=="__main__":
p=PeerInfo("ahmed",[1,2,3,4],80)
printp
print"alias:",p.alias
print"files:",p.sharedFiles
print"port:",p.listeningPort
Peer
#!bin/python
importsocket
importsys
importos
importthreading
fromutilsimportserialize,deserialize,PeerInfo
importrandomasrnd
classPeer(object):
def__init__(self,alias,serverAddr=(),sharedFiles=[]):
self.alias=alias
self.serverAddr=serverAddr
self.sharedFiles=sharedFiles
self.tcpClient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.tcpClient.connect(self.serverAddr)
self.BUF=1024
self.listeningPort=rnd.randint(8081,10000)
self.pInfo=PeerInfo(self.alias,self.sharedFiles,self.listeningPort)
print"\nConnectedtoserver..."
self.tClientToServer=threading.Thread(target=self.clientToServerHandler,args=[])
self.tClientToServer.start()
#listenforconnectionsinbackground..
self.addr=('',self.listeningPort)
self.listener=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.listener.bind(self.addr)
self.tListening=threading.Thread(target=self.listeningHandler,args=[])
self.tListening.start()
defregisterAtServer(self):
msg=("/register",self.alias,self.sharedFiles,self.listeningPort)
self.tcpClient.send(serialize(msg))
defclientToServerHandler(self):
print"StartChatting.."
#firstregisterthefiles...
self.registerAtServer()
whileTrue:
tServerToClient=threading.Thread(target=self.serverToClientHandler,args=[])
tServerToClient.start()
data=raw_input()
ifnotdata:continue
ifdata.lower=="exit":exit()
ifdata.split("")[0]=="/fetch":
fileneeded=data.split("")[1]
addr=data.split("")[2]
tFetchFile=threading.Thread(target=self.fetchFile,args=[addr,fileneeded])
tFetchFile.start()
else:
msg=self.alias+":"+data
self.tcpClient.send(serialize([msg]))
defserverToClientHandler(self):
whileTrue:
data=deserialize(self.tcpClient.recv(self.BUF))
ifnotdata:break
ifisinstance(data,list):#data['tina:hi']
printdata[0]
else:
printdata
deffetchFile(self,addr,fileneeded):
#addrisformated=>addr:listeningPort
endPoint=addr.split(":")[0],int(addr.split(":")[1])
fetchTCPClient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
fetchTCPClient.connect(endPoint)
fetchTCPClient.sendall(serialize(("/fetch",fileneeded)))
tDownloadFile=threading.Thread(target=self.downloadFile,args=[fetchTCPClient,fileneeded])
tDownloadFile.start()
defdownloadFile(self,fetchTCPClient,fileneeded):
##try:
##f=file(fileneeded,"wb")
##whileTrue:
##dataRcvd=fetchTCPClient.recv(self.BUF)
##ifnotdataRcvd:break
##f.write(dataRcvd)
##
##print"FileDownloaded!"
##
##exceptException,e:
##print"Error:",e
##
##finally:
##print"Closingthefile.."
##fetchTCPClient.close()
##f.close()
f=file(fileneeded,"wb")
whileTrue:
try:
buf=fetchTCPClient.recv(self.BUF)
ifnotbuf:
break
f.write(buf)
exceptEOFError,eofErr:
print"EOFError:",eofErr
exceptException,e:
print"Error:",e
break
print"FileDownloaded!"
f.close()
fetchTCPClient.close()
deflisteningHandler(self):
self.listener.listen(5)
whileTrue:
clientSocket,clientAddr=self.listener.accept()
tClientHandling=threading.Thread(target=self.clientHandler,args=[clientSocket])
tClientHandling.start()
defclientHandler(self,clientSocket):
rcvd=clientSocket.recv(self.BUF)
data=deserialize(rcvd)
ifisinstance(data,tuple):
ifdata[0]=="/fetch":#goon..
fileneeded=data[1]#(/fetch,fileneeded,from)
print"FileRequest:",fileneeded
f=file(fileneeded,"rb")
whileTrue:
try:
buf=f.read(self.BUF)
ifnotbuf:
break
clientSocket.send(buf)
exceptException,e:
print"Error:",e
break
f.close()
clientSocket.close()
print"Copied!"
if__name__=="__main__":
alias=raw_input("Alias:")
sharedFiles=os.listdir(os.getcwd())
peer=Peer(alias,('localhost',8080),sharedFiles)
trick AppwithaBug
-1 ) marshal pickle serialize(
-2 )
-1
)
(
stdlib ForkingMixIn
ThreadingMixIn
) sqlite3 (MySQL
-2 resume
-3 " LOG "print
-4 DiscoveryServer WebService
-5
-6 PeerInfo
FTPing
) ftplib (FTP
-1
importftplib
-2
"HOST="YOUR_HOST
"USER="YOUR_USERNAME
"PASSWD="YOUR_PASSWORD
-3 FTP
)(ftp=ftplib.FTP
-5 login user,password
)ftp.login(USER,PASSWD
-6
)(getwelcome
)rename(old,new
old new
cwd(path)
currentworkingdirectory
)(pwd
mkd(path)
path
delete(f)
f
)rmd(d
d
size(f)
f
quit()
QUIT
close()
set_pasv(boolean)
passivemode
)]]retrbinary(command,callback[,maxblocksize[,rest
RETRf callback block
)]storbinary(cmd,file[,block
STOR file
abort()
listing p
ftplib.py
)dir(p
XMLRPCwhat?
XMLRPC
HTTP RemoteProcedureCall XMLRPC
http://en.wikipedia.org/wiki/XMLRPC
#!bin/python
fromSimpleXMLRPCServerimportSimpleXMLRPCServer,SimpleXMLRPCRequestHandler
fromSocketServerimportThreadingMixIn
classGreeter(object):
defhi(self):
"""Returnshimessage"""
return"Hi"
defbye(self):
"""Returnsbyemessage"""
return"Bye"
defsay(self,what):
"""ReturnsSimonesaysmessage"""
return"Simonesays:"+what
classMyServer(ThreadingMixIn,SimpleXMLRPCServer):
pass
deftest():
addr=('',40002)
srvr=MyServer(addr,SimpleXMLRPCRequestHandler)
srvr.register_instance(Greeter())
srvr.register_introspection_functions()
srvr.serve_forever()
#print"Started..."
if__name__=="__main__":
test()
SocketServer ThreadingMixIn)
SimpleXMLRPCServer
classGreeter(object):
defhi(self):
"""Returnshimessage"""
return"Hi"
defbye(self):
"""Returnsbyemessage"""
return"Bye"
defsay(self,what):
"""ReturnsSimonesaysmessage"""
return"Simonesays:"+what
HTTP
register_instance SimpleXMLRPCServer
register_introspection_functions
system.methodSignature ) ( system.listMethods
methodHelp ( retrun )
srvr.register_instance(Greeter())
srvr.register_introspection_functions()
importxmlrpclib
s=xmlrpclib.ServerProxy('http://localhost:40002')
prints.system.listMethods()
prints.hi()
prints.bye()
prints.say("Something")
prints.system.methodHelp('say')
ServerProxy -1
s=xmlrpclib.ServerProxy('http://localhost:40002')
system.listMethods -2
bye hi -3
prints.hi()
prints.bye()
say -4
prints.say("Something")
striky@strikydesktop:~/workspace/pytut/src$pythonxmlrpcclient1.py
['bye','hi','say','system.listMethods','system.methodHelp','system.methodSignature']
Hi
Bye
Simonesays:Something
ReturnsSimonesaysmessage
documentation DocXMLRPCServer
DocXMLRPCServer
set_server_title set_server_name
set_server_documenation
fromDocXMLRPCServerimportDocXMLRPCServer,DocXMLRPCRequestHandler
fromSocketServerimportThreadingMixIn
classGreeter(object):
defhi(self):
"""Returnshimessage"""
return"Hi"
defbye(self):
"""Returnsbyemessage"""
return"Bye"
defsay(self,what):
"""ReturnsSimonesaysmessage"""
return"Simonesays:"+what
classMyServer(ThreadingMixIn,DocXMLRPCServer):
pass
deftest():
addr=('',40002)
srvr=MyServer(addr,DocXMLRPCRequestHandler)
##servermethods...
srvr.set_server_title("MyFirstDocXMLRPCServer")
srvr.set_server_name("GreeterDocXMLRPCServer")
srvr.set_server_documentation("GreeterDocXMLRPCServerisusedforlearningXMLRPC")
srvr.register_instance(Greeter())
srvr.register_introspection_functions()
srvr.serve_forever()
#print"Started..."
if__name__=="__main__":
test()
##Ruby
striky@strikydesktop:~$irb
irb(main):001:0>require"xmlrpc/client"
=>true
irb(main):002:0>require"pp"
=>true
irb(main):004:0>s=XMLRPC::Client.new2("http://localhost:40002")
=>#<XMLRPC::Client:0xb7aa2a50@user=nil,@proxy_port=nil,@auth=nil,@cookie=nil,@create=nil,
@port=40002,@http=#<Net::HTTPlocalhost:40002open=false>,@proxy_host=nil,@http_last_response=nil,
@parser=nil,@timeout=30,@path="/RPC2",@password=nil,@http_header_extra=nil,@use_ssl=false,
@host="localhost">
irb(main):005:0>s
=>#<XMLRPC::Client:0xb7aa2a50@user=nil,@proxy_port=nil,@auth=nil,@cookie=nil,@create=nil,
@port=40002,@http=#<Net::HTTPlocalhost:40002open=false>,@proxy_host=nil,@http_last_response=nil,
@parser=nil,@timeout=30,@path="/RPC2",@password=nil,@http_header_extra=nil,@use_ssl=false,
@host="localhost">
irb(main):006:0>s.call('hi')
=>"Hi"
irb(main):007:0>s.call('bye')
=>"Bye"
irb(main):008:0>s.call('say',"Hello,World!")
=>"Simonesays:Hello,World!"
QuoteoftheDay
" "
quotes.txt -1
Never pretend to a love which you do not actually feel, for love is not
ours to command. --Alan Watts
To love deeply in one direction makes us more loving in all others.
--Anne-Sophie Swetchine
There is always some madness in love. But there is also always some reason
in madness. --Friedrich Nietzsche
Life is wasted on the living. --Douglas Adams
Life is just a chance to grow a soul. - A. Powell
quoter -2
#!bin/python
from__future__importwith_statement
importrandomasrnd
defget_quotes(f="quotes.txt"):
###quotesareseparatedby\n
withopen(f)asfh:
lines=fh.read()
quotes=lines.split("\n")
returnquotes
defget_random_quote(quotes=get_quotes()):
returnrnd.choice(quotes)
if__name__=="__main__":
printget_random_quote()
d: with_statement
random
quotes.txt f get_quotes *
try/except with
strip " " )
fromSocketServerimportTCPServer,StreamRequestHandler,ThreadingMixIn
importthreading
importquoter
fromdjango.utilsimportdaemonize
classMyServer(ThreadingMixIn,TCPServer):
pass
classMyStreamRequestHandler(StreamRequestHandler):
defhandle(self):
self.request.send(self.get_quote()+"\r\n")
defget_quote(self):
returnquoter.get_random_quote()
defgo(endpoint=('',58000)):
addr=endpoint
tcpServer=MyServer(addr,MyStreamRequestHandler)
tcpServer.allow_reuse_address=1
print"Serverstarted..."
tcpServer.serve_forever()#inf.loop
if__name__=="__main__":
try:
daemonize.become_daemon()
go()
exceptKeyboardInterrupt:
exit()
django.utils daemonize
become_daemon
!daemon
daemonize.become_daemon
importos
importsys
ifos.name=='posix':
defbecome_daemon(our_home_dir='.',out_log='/dev/null',
err_log='/dev/null',umask=022):
"RobustlyturnintoaUNIXdaemon,runninginour_home_dir."
#Firstfork
try:
ifos.fork()>0:
sys.exit(0)#killoffparent
exceptOSError,e:
sys.stderr.write("fork#1failed:(%d)%s\n"%(e.errno,e.strerror))
sys.exit(1)
os.setsid()
os.chdir(our_home_dir)
os.umask(umask)
#Secondfork
try:
ifos.fork()>0:
os._exit(0)
exceptOSError,e:
sys.stderr.write("fork#2failed:(%d)%s\n"%(e.errno,e.strerror))
os._exit(1)
si=open('/dev/null','r')
so=open(out_log,'a+',0)
se=open(err_log,'a+',0)
os.dup2(si.fileno(),sys.stdin.fileno())
os.dup2(so.fileno(),sys.stdout.fileno())
os.dup2(se.fileno(),sys.stderr.fileno())
#Setcustomfiledescriptorssothattheygetproperbuffering.
sys.stdout,sys.stderr=so,se
else:
defbecome_daemon(our_home_dir='.',out_log=None,err_log=None,umask=022):
"""
Ifwe'renotrunningunderaPOSIXsystem,justsimulatethedaemon
modebydoingredirectionsanddirectorychanging.
"""
os.chdir(our_home_dir)
os.umask(umask)
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
iferr_log:
sys.stderr=open(err_log,'a',0)
else:
sys.stderr=NullDevice()
ifout_log:
sys.stdout=open(out_log,'a',0)
else:
sys.stdout=NullDevice()
classNullDevice:
"Awriteableobjectthatwritestonowherelike/dev/null."
defwrite(self,s):
pass
telnetlocalhost58000
striky@strikydesktop:~/workspace/pytut/src/nettut/quoter$telnetlocalhost58000
Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
Lifeisjustachancetogrowasoul.A.Powell
Connectionclosedbyforeignhost.
Chapter13(PythonontheWEB)
Grok
Zope
easy_installgrokproject
striky@strikydesktop:~/workspace/pytut/src/nettut$mkdirgroktut
striky@strikydesktop:~/workspace/pytut/src/nettut$cdgroktut/
grokproject
striky@strikydesktop:~/workspace/pytut/src/nettut/groktut$grokprojectFirstProject
grok
Enteruser(Nameofaninitialadministratoruser):grok
grok ( getpass )
Enterpasswd(Passwordfortheinitialadministratoruser):
Downloadinginfoaboutversions...
Creatingdirectory./FirstProject
Invokingzc.buildout...
Develop:'/home/striky/workspace/pytut/src/nettut/groktut/FirstProject/.'
Installingeggbasket.
Gettingdistributionfor'grok==0.14.1'.
eggbasket:Distributionsarenotinstalled.Atarballwillbedownloaded.
eggbasket:Distributionsarenotinstalled.Atarballwillbedownloaded.
eggbasket:Downloadinghttp://grok.zope.org/releaseinfo/grokeggs0.14.1.tgz...
eggbasket:Downloadinghttp://grok.zope.org/releaseinfo/grokeggs0.14.1.tgz...
eggbasket:Finisheddownloading.
eggbasket:Finisheddownloading.
eggbasket:Extractingtarballcontents...
eggbasket:Extractingtarballcontents...
eggbasket:Installingeggsto/home/striky/.buildout/eggswhichwilltakeawhile...
eggbasket:Installingeggsto/home/striky/.buildout/eggswhichwilltakeawhile...
Gettingdistributionfor'grok==0.14.1'.
Gotgrok0.14.1.
striky@strikydesktop:~/workspace/pytut/src/nettut/groktut$cdFirstProject/
tree
striky@strikydesktop:~/workspace/pytut/src/nettut/groktut/FirstProject$tree
.
|bin
||buildout
||i18nextract
||i18nmergeall
||i18nstats
||test
|`zopectl
|bootstrap.py
|buildout.cfg
|developeggs
|`FirstProject.egglink
|parts
||app
|||debugzope
|||runzope
||`site.zcml
||data
||i18n
||`configure.zcml
||test
|`zopectl
||zdaemon.conf
|`zope.conf
|setup.py
|src
||FirstProject.egginfo
|||PKGINFO
|||SOURCES.txt
|||dependency_links.txt
|||entry_points.txt
|||notzipsafe
|||requires.txt
||`top_level.txt
|`firstproject
||__init__.py
||app.py
||app.txt
||app_templates
||`index.pt
||configure.zcml
||ftesting.zcml
||static
||`README.txt
|`tests.py
`versions.cfg
13directories,32files
static templates
zope
hello
localhost:8012/hello
templates firstprojct/app_templates/
index.pt
striky@strikydesktop:~/workspace/pytut/src/nettut/groktut/FirstProject/src/firstproject$tree
.
|__init__.py
|__init__.pyc
|app.py
|app.pyc
|app.txt
|app_templates
|`index.pt
|configure.zcml
|ftesting.zcml
|static
|`README.txt
`tests.py
2directories,10files
app_templates index.pt
<html>
<head>
</head>
<body>
<h1>Congratulations!</h1>
<p>YourGrokapplicationisupandrunning.
Edit<code>firstproject/app_templates/index.pt</code>tochange
thispage.</p>
</body>
</html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Congratulations!</h1>
<p>
<b>Grok</b>isup&running
</p>
</body>
</html>
localhost:8012/hello
importgrok
classFirstproject(grok.Application,grok.Container):
pass
classIndex(grok.View):
pass#seeapp_templates/index.pt
Hi,Bye views 2
classHi(grok.View):
pass#rendersapp_templates/hi.pt
classBye(grok.View):
pass#rendersapp_templates/bye.pt
<html>
<head>
<title>Hi</title>
</head>
<body>
<h1>WelcometoGrok!</h1>
</body>
</html>
bye.pt
<html>
<head>
<title>Bye</title>
</head>
<body>
<h1>Havetogo:(</h1>
</body>
></html
hiview
bye.view
) 8080 zope :
(
[zopectl] buildout.cfg
address=localhost:8012
#controllingthelisteningport,rerunbuildoutscript.
buildout
striky@strikydesktop:~/workspace/pytut/src/nettut/groktut/FirstProject$bin/buildout
Develop:'/home/striky/workspace/pytut/src/nettut/groktut/FirstProject/.'
Uninstallingzopectl.
Updatingeggbasket.
Updatingapp.
Updatingdata.
Installingzopectl.
Generatedscript'/home/striky/workspace/pytut/src/nettut/groktut/FirstProject/bin/zopectl'.
Updatingi18n.
Therecipefori18ndoesn'tdefineanupdatemethod.Usingitsinstallmethod.
i18n:settingupi18ntools
Updatingtest.
http://grok.zope.org
Webpy
)
(
easyinstallweb.py
http://webpy.org
setup
pythonsetup.pyinstall
importweb
urls=(
'/(.*)','index'
)
classindex:
defGET(self,name):
return'Hello,World!'
app=web.application(urls,globals())
if__name__=="__main__":
app.run()
-1 webpy
importweb
-2 urls tuple
''/(.*)', 'index
view index
classindex:
defGET(self,name):
'!return'Hello,World
app=web.application(urls,globals())
run
)(app.run
3001
8080
striky@strikydesktop:~/workspace/pytut/src/nettut/webpytut$pythonhello.py3001
http://webpy.org/src
webpy
http://k4ml.com/wiki/python/webpy/simpleblog
TheBigThree
Pylons TurboGears Django 3
Pylons
python,ruby,perl Pylons
http://pylonshq.com/
HelloWorld:Pylons
striky@strikydesktop:~/workspace/pytut/src/nettut$pastercreatetpylonshelloworld
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linuxi686.egg/dispatch/__init__.py:98:
Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/CherryPy2.3.0py2.5.egg/cherrypy/lib/profiler.py:54:UserWarning:Your
installationofPythondoesn'thaveaprofilemodule.Ifyou'reonDebian,youcanaptgetpython2.4profiler
fromnonfreeinaseparatestep.Seehttp://www.cherrypy.org/wiki/ProfilingOnDebianfordetails.
warnings.warn(msg)
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:239:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:263:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:281:Warning:'as'willbecomeareservedkeywordinPython2.6
Selectedandimpliedtemplates:
Pylons#pylonsPylonsapplicationtemplate
Variables:
egg:helloworld
package:helloworld
project:helloworld
Entertemplate_engine(mako/genshi/jinja/etc:Templatelanguage)['mako']:
Entersqlalchemy(True/False:IncludeSQLAlchemy0.4configuration)[False]:
Entergoogle_app_engine(True/False:SetupdefaultappropriateforGoogleAppEngine)[False]:
Creatingtemplatepylons
Creatingdirectory./helloworld
Recursinginto+package+
Creating./helloworld/helloworld/
Copyingtemplates/default_project/+package+/__init__.py_tmplto./helloworld/helloworld/__init__.py
Recursingintoconfig
Creating./helloworld/helloworld/config/
Copyingtemplates/default_project/+package+/config/__init__.py_tmplto
./helloworld/helloworld/config/__init__.py
Copyingtemplates/default_project/+package+/config/deployment.ini_tmpl_tmplto./helloworld/helloworld/
config/deployment.ini_tmpl
Copyingtemplates/default_project/+package+/config/environment.py_tmplto
./helloworld/helloworld/config/environment.py
Copyingtemplates/default_project/+package+/config/middleware.py_tmplto
./helloworld/helloworld/config/middleware.py
Copyingtemplates/default_project/+package+/config/routing.py_tmplto
./helloworld/helloworld/config/routing.py
Recursingintocontrollers
Creating./helloworld/helloworld/controllers/
Copyingtemplates/default_project/+package+/controllers/__init__.py_tmplto
./helloworld/helloworld/controllers/__init__.py
Copyingtemplates/default_project/+package+/controllers/error.py_tmplto
./helloworld/helloworld/controllers/error.py
Recursingintolib
Creating./helloworld/helloworld/lib/
Copyingtemplates/default_project/+package+/lib/__init__.py_tmplto
./helloworld/helloworld/lib/__init__.py
Copyingtemplates/default_project/+package+/lib/app_globals.py_tmplto
./helloworld/helloworld/lib/app_globals.py
Copyingtemplates/default_project/+package+/lib/base.py_tmplto./helloworld/helloworld/lib/base.py
Copyingtemplates/default_project/+package+/lib/helpers.py_tmplto./helloworld/helloworld/lib/helpers.py
Recursingintomodel
Creating./helloworld/helloworld/model/
Copyingtemplates/default_project/+package+/model/__init__.py_tmplto
./helloworld/helloworld/model/__init__.py
Recursingintopublic
Creating./helloworld/helloworld/public/
Copyingtemplates/default_project/+package+/public/bg.pngto./helloworld/helloworld/public/bg.png
Copyingtemplates/default_project/+package+/public/index.html_tmplto
./helloworld/helloworld/public/index.html
Copyingtemplates/default_project/+package+/public/pylonslogo.gifto
./helloworld/helloworld/public/pylonslogo.gif
Recursingintotemplates
Creating./helloworld/helloworld/templates/
Recursingintotests
Creating./helloworld/helloworld/tests/
Copyingtemplates/default_project/+package+/tests/__init__.py_tmplto
./helloworld/helloworld/tests/__init__.py
Recursingintofunctional
Creating./helloworld/helloworld/tests/functional/
Copyingtemplates/default_project/+package+/tests/functional/__init__.py_tmplto./helloworld/helloworld/
tests/functional/__init__.py
Copyingtemplates/default_project/+package+/tests/test_models.py_tmplto
./helloworld/helloworld/tests/test_models.py
Copyingtemplates/default_project/+package+/websetup.py_tmplto./helloworld/helloworld/websetup.py
Copyingtemplates/default_project/MANIFEST.in_tmplto./helloworld/MANIFEST.in
Copyingtemplates/default_project/README.txt_tmplto./helloworld/README.txt
Copyingtemplates/default_project/development.ini_tmplto./helloworld/development.ini
Recursingintodocs
Creating./helloworld/docs/
Copyingtemplates/default_project/docs/index.txt_tmplto./helloworld/docs/index.txt
Copyingtemplates/default_project/ez_setup.pyto./helloworld/ez_setup.py
Copyingtemplates/default_project/setup.cfg_tmplto./helloworld/setup.cfg
Copyingtemplates/default_project/setup.py_tmplto./helloworld/setup.py
Copyingtemplates/default_project/test.ini_tmplto./helloworld/test.ini
Running/usr/bin/pythonsetup.pyegg_info
3
mako templateengine -1
sqlalchemy -2
GoogleAppEngine -3
|MANIFEST.in
|README.txt
|development.ini
|docs
|`index.txt
|ez_setup.py
|helloworld
||__init__.py
||config
|||__init__.py
|||deployment.ini_tmpl
|||environment.py
|||middleware.py
||`routing.py
||controllers
|||__init__.py
||`error.py
||lib
|||__init__.py
|||app_globals.py
|||base.py
||`helpers.py
||model
||`__init__.py
||public
|||bg.png
|||index.html
||`pylonslogo.gif
||templates
||tests
|||__init__.py
|||functional
|||`__init__.py
||`test_models.py
|`websetup.py
|helloworld.egginfo
||PKGINFO
||SOURCES.txt
||dependency_links.txt
||entry_points.txt
||notzipsafe
||paster_plugins.txt
||requires.txt
|`top_level.txt
|setup.cfg
|setup.py
`test.ini
(webpy grok views actions ) controller
striky@strikydesktop:~/workspace/pytut/src/nettut/helloworld$pastercontrollerhello
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linuxi686.egg/dispatch/__init__.py:98:
Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/CherryPy2.3.0py2.5.egg/cherrypy/lib/profiler.py:54:UserWarning:Your
installationofPythondoesn'thaveaprofilemodule.Ifyou'reonDebian,youcanaptgetpython2.4profiler
fromnonfreeinaseparatestep.Seehttp://www.cherrypy.org/wiki/ProfilingOnDebianfordetails.
warnings.warn(msg)
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:239:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:263:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:281:Warning:'as'willbecomeareservedkeywordinPython2.6
Creating/home/striky/workspace/pytut/src/nettut/helloworld/helloworld/controllers/hello.py
Creating/home/striky/workspace/pytut/src/nettut/helloworld/helloworld/tests/functional/test_hello.py
striky@strikydesktop:~/workspace/pytut/src/nettut/helloworld$
helloworld/controllers/hello
importlogging
frompylonsimportrequest,response,session,tmpl_contextasc
frompylons.controllers.utilimportabort,redirect_to
fromhelloworld.lib.baseimportBaseController,render
#fromhelloworldimportmodel
log=logging.getLogger(__name__)
classHelloController(BaseController):
defindex(self):
#Returnarenderedtemplate
#returnrender('/template.mako')
#or,Returnaresponse
return'HelloWorld'
mysite.com/controller/view
mysite.com/hello/index
action hello ( )
striky@strikydesktop:~/workspace/pytut/src/nettut/helloworld$pasterservereloaddevelopment.ini
development.ini
hello/index
TurboGears
kid templates SQLObject SQLAlchemy
/http://turbogears.org
http://docs.turbogears.org/1.0/Install
tgsetup.py
http://www.turbogears.org/download/tgsetup.py
striky@strikydesktop:~/Desktop$sudopythontgsetup.py
[sudo]passwordforstriky:
Sorry,tryagain.
[sudo]passwordforstriky:
TurboGearsInstaller
Beginningsetuptools/EasyInstallinstallationandTurboGearsdownload
SearchingforTurboGears==1.0.8
Readinghttp://www.turbogears.org/download/
Readinghttp://pypi.python.org/simple/TurboGears/
Readinghttp://www.turbogears.org
Readinghttp://www.turbogears.org/
Readinghttp://www.turbogears.org/download/filelist.html
Bestmatch:TurboGears1.0.8
Downloadinghttp://files.turbogears.org/eggs/TurboGears1.0.8py2.5.egg
ProcessingTurboGears1.0.8py2.5.egg
removing'/usr/lib/python2.5/sitepackages/TurboGears1.0.8py2.5.egg'(andeverythingunderit)
creating/usr/lib/python2.5/sitepackages/TurboGears1.0.8py2.5.egg
ExtractingTurboGears1.0.8py2.5.eggto/usr/lib/python2.5/sitepackages
RemovingTurboGears1.0.7fromeasyinstall.pthfile
AddingTurboGears1.0.8toeasyinstall.pthfile
Installingtgadminscriptto/usr/bin
Installed/usr/lib/python2.5/sitepackages/TurboGears1.0.8py2.5.egg
Readinghttp://files.turbogears.org/eggs/
ProcessingdependenciesforTurboGears==1.0.8
SearchingforExtremes>=1.1
Readinghttp://pypi.python.org/simple/Extremes/
Bestmatch:Extremes1.1
Downloadinghttp://pypi.python.org/packages/2.5/E/Extremes/Extremes1.1
py2.5.egg#md5=4015e2546295858558cca16faca5f34f
ProcessingExtremes1.1py2.5.egg
MovingExtremes1.1py2.5.eggto/usr/lib/python2.5/sitepackages
AddingExtremes1.1toeasyinstall.pthfile
Installed/usr/lib/python2.5/sitepackages/Extremes1.1py2.5.egg
SearchingforPyProtocols>=1.0a0devr2302
Readinghttp://pypi.python.org/simple/PyProtocols/
Readinghttp://peak.telecommunity.com/PyProtocols.html
Readinghttp://peak.telecommunity.com/dist/
Bestmatch:PyProtocols1.0a0devr2302
Downloadinghttp://files.turbogears.org/eggs/PyProtocols1.0a0dev_r2302py2.5linuxi686.egg
ProcessingPyProtocols1.0a0dev_r2302py2.5linuxi686.egg
MovingPyProtocols1.0a0dev_r2302py2.5linuxi686.eggto/usr/lib/python2.5/sitepackages
AddingPyProtocols1.0a0devr2302toeasyinstall.pthfile
Installed/usr/lib/python2.5/sitepackages/PyProtocols1.0a0dev_r2302py2.5linuxi686.egg
FinishedprocessingdependenciesforTurboGears==1.0.8
HelloWorld:TG
tgadminquickstart
striky@strikydesktop:~/workspace/pytut/src/nettut$tgadminquickstart
/usr/lib/python2.5/sitepackages/CherryPy2.3.0py2.5.egg/cherrypy/lib/profiler.py:54:UserWarning:Your
installationofPythondoesn'thaveaprofilemodule.Ifyou'reonDebian,youcanaptgetpython2.4profiler
fromnonfreeinaseparatestep.Seehttp://www.cherrypy.org/wiki/ProfilingOnDebianfordetails.
warnings.warn(msg)
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linuxi686.egg/dispatch/__init__.py:98:
Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:239:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:263:Warning:'as'willbecomeareservedkeywordinPython2.6
/usr/lib/python2.5/sitepackages/RuleDispatch0.5a1.dev_r2506py2.5linux
i686.egg/dispatch/predicates.py:281:Warning:'as'willbecomeareservedkeywordinPython2.6
Enterprojectname:hello
Enterpackagename[hello]:hello
DoyouneedIdentity(usernames/passwords)inthisproject?[no]
Selectedandimpliedtemplates:
TurboGears#tgbasetgbasetemplate
TurboGears#turbogearswebframework
Variables:
egg:hello
elixir:False
identity:none
package:hello
project:hello
sqlalchemy:False
sqlobject:True
sqlobjectversion:SQLObject>=0.10.1
Creatingtemplatetgbase
Creatingdirectory./hello
Recursinginto+einame+.egginfo
Creating./hello/hello.egginfo/
CopyingPKGINFOto./hello/hello.egginfo/PKGINFO
Copyingpaster_plugins.txtto./hello/hello.egginfo/paster_plugins.txt
Copyingsqlobject.txt_tmplto./hello/hello.egginfo/sqlobject.txt
Recursinginto+package+
Creating./hello/hello/
Copying__init__.pyto./hello/hello/__init__.py
Copyingrelease.py_tmplto./hello/hello/release.py
Recursingintostatic
Creating./hello/hello/static/
Recursingintocss
Creating./hello/hello/static/css/
Skippingfile/usr/lib/python2.5/sitepackages/TurboGears1.0.8py2.5.egg/turbogears/qstemplates/qsbase/
+package+/static/css/empty_tmpl
Recursingintoimages
Creating./hello/hello/static/images/
Copyingfavicon.icoto./hello/hello/static/images/favicon.ico
Copyingtg_under_the_hood.pngto./hello/hello/static/images/tg_under_the_hood.png
Copyingunder_the_hood_blue.pngto./hello/hello/static/images/under_the_hood_blue.png
Recursingintojavascript
Creating./hello/hello/static/javascript/
Skippingfile/usr/lib/python2.5/sitepackages/TurboGears1.0.8py2.5.egg/turbogears/qstemplates/qsbase/
+package+/static/javascript/empty_tmpl
Recursingintotemplates
Creating./hello/hello/templates/
Copying__init__.pyto./hello/hello/templates/__init__.py
Creatingtemplateturbogears
Recursinginto+package+
Copyingcommands.py_tmplto./hello/hello/commands.py
Recursingintoconfig
Creating./hello/hello/config/
Copying__init__.pyto./hello/hello/config/__init__.py
Copyingapp.cfg_tmplto./hello/hello/config/app.cfg
Copyinglog.cfg_tmplto./hello/hello/config/log.cfg
Copyingcontrollers.py_tmplto./hello/hello/controllers.py
Copyingjson.py_tmplto./hello/hello/json.py
Copyingmodel.py_tmplto./hello/hello/model.py
Recursingintostatic
Recursingintocss
Copyingstyle.cssto./hello/hello/static/css/style.css
Recursingintoimages
Copyingheader_inner.pngto./hello/hello/static/images/header_inner.png
Copyinginfo.pngto./hello/hello/static/images/info.png
Copyingok.pngto./hello/hello/static/images/ok.png
Recursingintotemplates
Copyinglogin.kidto./hello/hello/templates/login.kid
Copyingmaster.kidto./hello/hello/templates/master.kid
Copyingwelcome.kidto./hello/hello/templates/welcome.kid
Recursingintotests
Creating./hello/hello/tests/
Copying__init__.pyto./hello/hello/tests/__init__.py
Copyingtest_controllers.py_tmplto./hello/hello/tests/test_controllers.py
Copyingtest_model.py_tmplto./hello/hello/tests/test_model.py
CopyingREADME.txt_tmplto./hello/README.txt
Copyingdev.cfg_tmplto./hello/dev.cfg
Copyingsampleprod.cfg_tmplto./hello/sampleprod.cfg
Copyingsetup.py_tmplto./hello/setup.py
Copyingstart+package+.py_tmplto./hello/starthello.py
Copyingtest.cfg_tmplto./hello/test.cfg
Running/usr/bin/pythonsetup.pyegg_info
Manuallycreatingpaster_plugins.txt(deprecated!passapaster_pluginskeywordtosetup()instead)
AddingTurboGearstopaster_plugins.txt
runningegg_info
paster_pluginsnotsetinsetup(),buthello.egginfo/paster_plugins.txtexists
writingrequirementstohello.egginfo/requires.txt
writinghello.egginfo/PKGINFO
writingtoplevelnamestohello.egginfo/top_level.txt
writingdependency_linkstohello.egginfo/dependency_links.txt
writingentrypointstohello.egginfo/entry_points.txt
readingmanifestfile'hello.egginfo/SOURCES.txt'
writingmanifestfile'hello.egginfo/SOURCES.txt'
striky@strikydesktop:~/workspace/pytut/src/nettut$
dev.cfg
server.socket_port=40003
sqlite
"sqlobject.dburi="sqlite://%(current_dir_uri)s/devdata.sqlite
..
startscript starthello.py
localhost:40003
importturbogearsastg
fromturbogearsimportcontrollers,expose,flash
#fromhelloimportmodel
#importlogging
#log=logging.getLogger("hello.controllers")
classRoot(controllers.RootController):
@expose(template="hello.templates.welcome")
defindex(self):
importtime
#log.debug("HappyTurboGearsControllerRespondingForDuty")
flash("Yourapplicationisnowrunning")
returndict(now=time.ctime())
Edit<spanclass="code">dev.cfg</span>to<a
href="http://docs.turbogears.org/1.0/GettingStarted/UseDatabase">useadifferentbackend</a>,orstartwitha
preconfiguredSQLitedatabase.<br/>
Usescript<spanclass="code">tgadminsqlcreate</span>tocreatethedatabasetables.</p>
</li>
<liclass="getting_started">
<h3>View</h3>
<p>Edit<ahref="http://docs.turbogears.org/1.0/GettingStarted/Kid">htmlliketemplates</a>inthe
<spanclass="code">/templates</span>folder;<br/>
Putall<ahref="http://docs.turbogears.org/1.0/StaticFiles">staticcontents</a>inthe<span
class="code">/static</span>folder.</p>
</li>
<liclass="getting_started">
<h3>Controller</h3>
<p>Edit<spanclass="code">controllers.py</span>and<a
href="http://docs.turbogears.org/1.0/GettingStarted/CherryPy">buildyour
websitestructure</a>withthesimplicityofPythonobjects.<br/>
TurboGearswillautomaticallyreloaditselfwhenyoumodifyyourproject.</p>
</li>
</ol>
<divclass="notice">Ifyoucreatesomethingcool,please<a
href="http://groups.google.com/group/turbogears">letpeopleknow</a>,andconsidercontributingsomething
backtothe<ahref="http://groups.google.com/group/turbogears">community</a>.</div>
</div>
<!Endofgetting_started>
</body>
</html>
greet action
RootController controllers.py
@expose(template='hello.templates.greet')
defgreet(self,who='World'):
returndict(g='Hello,'+who)
localhost:40003/hello/Ahmed
who
action
Django Web2Py
http://wiki.python.org/moin/WebFrameworks
Chapter14(ExtendingPython)
PureC
Extensions
++C CLike C Python
Python extensions
builtintypes C Python builtinmodules
(: sourcecode SystemCalls Clibfunctions encapsulation
Python C :
project python.h PythonAPI/C
(: Hello,World . header python.h :
helloMod.c -1
-2
#include<Python.h>
staticPyObject*hola(PyObject*self,PyObject*args)
{
if(!PyArg_ParseTuple(args,"",NULL))
returnNULL;
printf("Hola!");
Py_RETURN_NONE;
}
staticPyMethodDefHolaMethods[]=
{
{"hola",hola,METH_VARARGS,"printsHola\n"},
{NULL,NULL,0,NULL}
};
PyMODINIT_FUNC
inithola(void)
{
(void)Py_InitModule("hola",HolaMethods);
}
module hola
include pythonapiheader
>#include<Python.h
Object Python Pointer PyObject
function !Hola
)staticPyObject*hola(PyObject*self,PyObject*args
Function
Function Hola printf
;)"!printf("Hola
Py_RETURN_NONE;
fromdistutils.coreimportsetup,Extension
modExt=Extension('hola',sources=['hola.c'])
setup(name='HolaPackage',
version='1.0',
description='Simpledemo',
ext_modules=[modExt])
:
Disutils.core setup,Extension -1
ExtensionObject -2
modExt=Extension('hola',sources=['hola.c'])
extension source
extensions Package setupscript -3
setup(name='HolaPackage',
version='1.0',
description='Simpledemo',
ext_modules=[modExt])
Pythonsetup.pybuild
Package Install
Pythonsetup.pyinstall
HolaModule
HolaTest.py TestScript -1
holaModule import -2
importhola
holafunction -3
hola.hola()
#output:
Hola!
Function return -4
printhola.hola()
#Output:
Hola!
None
MyABSFunction
staticPyObject*myabs(PyObject*self,PyObject*args)
{
intnumber;
if(!PyArg_ParseTuple(args,"i",&number))
returnNULL;
if(number<0){
number=number;
}
returnPy_BuildValue("i",number);
}
integer i Function
(CValue PythonValue ) number
myabsFunction ReturnType ( PyObject )PythonValue Return
PythonValue CValue
Py_BuildValue
number Integer i return
holaDictFunction
staticPyObject*holaDict(PyObject*self,PyObject*args)
{
constchar*key;
intvalue;
if(!PyArg_ParseTuple(args,"si",&key,&value))
returnNULL;
returnPy_BuildValue("{s:i}",key,value);//ReturnsaDict.
}
{s:i} DictionaryObject
Format List return
returnPy_BuildValue("[s,i]",key,value);//ReturnsaListobject
(s,i) Format Tuple return
holaTupleFunction
staticPyObject*holaTuple(PyObject*self,PyObject*args)
{
constchar*name;
intage;
if(!PyArg_ParseTuple(args,"si",&name,&age))
returnNULL;
returnPy_BuildValue("(s,i)",name,age);//ReturnsaTuple
}
divTwoFunction
staticPyObject*divTwo(PyObject*self,PyObject*args)
{
intfirst;
intsecond;
intresult;
if(!PyArg_ParseTuple(args,"ii",&first,&second))
returnNULL;
printf("First:%i\n",first);
printf("Second:%i\n",second);
if(second==0){//DivByZeroError!
PyErr_SetString(PyExc_ZeroDivisionError,"DivByZero");
returnNULL;//Getout!
}
result=first/second;
returnPy_BuildValue("i",result);
}
(( Interpreter) ! )Error 0
PyErr_SetString
DivByZero message PyExc_ZeroDivisionError Error
MethodsTable -2
staticPyMethodDefSimpleModuleMethods[]=
{
{"hola",hola,METH_VARARGS,"printsnameandage"},
{"myabs",myabs,METH_VARARGS,"returnstheabsofanumber"},
{"divTwo",divTwo,METH_VARARGS,"DIV2"},
{"holaTuple",holaTuple,METH_VARARGS,"returnsatuple"},
{"holaDict",holaDict,METH_VARARGS,"returnsadict"},
{NULL,NULL,0,NULL}
};
.. Array
Py_InitModuleFunction Module Initialize -3
PyMODINIT_FUNC
initsimplemodule(void)
{
(void)Py_InitModule("simplemodule",SimpleModuleMethods);
}
SetupScript -4
fromdistutils.coreimportsetup,Extension
modExt=Extension('simplemodule',sources=['simplemodule.c'])
setup(name='SimpleModPackage',
version='1.0',
description='hola,myabs',
ext_modules=[modExt])
#Output:
Name:Ahmed
Age:18
10
7
{'python':1}
('ahmed',999)
First:2
Second:0
Traceback(mostrecentcalllast):
File"C:\Python25\Projects\exten\smTest.py",line10,in<module>
printsm.divTwo(2,0)
ZeroDivisionError:DivByZero
References:
1ExtendingPython
2ProgrammingPython3rdEdition
Related:
1StyleGuideforCCode
2SWIG
3CXX
Swig
TODO...
ctypes
- libmagic extension
foreign Function library -magic number
C ctypes FFL
wrapper )
(
libmagicdev libmagic -1
magic.h -2
structures
#ifndef_MAGIC_H
#define_MAGIC_H
#include<sys/types.h>
#define
#define
#define
#define
#define
#define
..........
#define
MAGIC_NONE
MAGIC_DEBUG
MAGIC_SYMLINK
MAGIC_COMPRESS
MAGIC_DEVICES
MAGIC_MIME_TYPE
0x000000/*Noflags*/
0x000001/*Turnondebugging*/
0x000002/*Followsymlinks*/
0x000004/*Checkinsidecompressedfiles*/
0x000008/*Lookatthecontentsofdevices*/
0x000010/*ReturnonlytheMIMEtype*/
MAGIC_NO_CHECK_TROFF
0x000000/*Don'tcheckascii/troff*/
typedefstructmagic_set*magic_t;
magic_tmagic_open(int);
voidmagic_close(magic_t);
......
constchar*magic_file(magic_t,constchar*);
constchar*magic_descriptor(magic_t,int);
constchar*magic_buffer(magic_t,constvoid*,size_t);
FFL -3
fromctypesimport*
-4
MAGIC_NONE=0x000000
#Noflags
MAGIC_DEBUG=0x000001
#Turnondebugging
MAGIC_SYMLINK=0x000002
#Followsymlinks
MAGIC_COMPRESS=0x000004
#Checkinsidecompressedfiles
MAGIC_DEVICES=0x000008
#Lookatthecontentsofdevices
MAGIC_MIME_TYPE=0x000010
#ReturnonlytheMIMEtype
MAGIC_CONTINUE=0x000020
#Returnallmatches
MAGIC_MIME_ENCODING=0x000400
#ReturnonlytheMIMEencoding
#Definedforbackwardscompatibility;donothing
MAGIC_NO_CHECK_FORTRAN=0x000000
#Don'tcheckascii/fortran
MAGIC_NO_CHECK_TROFF=0x000000 #Don'tcheckascii/troff
-loading-
libmagic=CDLL("libmagic.so")#orevenbetter,checkctypes.util
ctypestype
Ctype
c_char
Char
c_wchar
wchar_t
c_byte
Char
c_ubyte
Unsignedchar
c+short
Short
c_ushort
Unsignedshort
c_int
Int
c_uint
Unsignedint
c_long
long
c_ulong
Unsignedlong
c_longlong
Longlong
c_ulonglong
Unsignedlonglong
c_float
Float
c_double
Double
c_longdouble
Longdouble
c_char_p
Char*(nullterminated)
c_wchar_p
wchar_t*(nullterminated)
c_void_p
Void*
types -5
magic_t=c_void_p #void pointer.
magic_t magic_open(int);
-6
( return )
int magic_t magic_open
magic_open=libmagic.magic_open
magic_open.restype=magic_t
magic_open.argtypes=[c_int]
char magic_t char magic_file
const char *magic_file(magic_t, const char *);
magic_file=libmagic.magic_file
magic_file.restype=c_char_
magic_file.argtypes=[magic_t,c_char_p]
defguess(filepath,flags):
mc=magic_open(flags)
magic_load(mc,None)
res=magic_file(mc,filepath)
magic_close(mc)
returnres
http://bitbucket.org/xmonader/libmagicbindings/
libmagic pymagic
PCRE binding ctypes
http://bitbucket.org/xmonader/pypcre/
)Chapter15(FunctionalPython
.. functools itertools
functools
reduce(function,iterable[,init])
reduce
sequence ""
#reduce(func,seq[,init])
printreduce((lambdax,y:x+y),[1,2,3,4,5])#15
#((((1+2)+3)+4)+5)
partial(func,*args,**kwargs)
- -
Currying
>>>defsayhi(to):
...print"Hi,",to
>>>f=lambdato="Ahmed":sayhi(to)
>>>f
<function<lambda>at0xb7df08b4>
>>>f()
Hi,Ahmed
partial
>>>part_f=partial(sayhi,"Ahmed")
>>>part_f()
Hi, Ahmed
>>>defsomeparty(*guests):
...
print"Visitors:"
...
forginguests:
...print"\t",g
>>>someparty("Ahmed")
Visitors:
Ahmed
>>>someparty("Ahmed","Mido")
Visitors:
Ahmed
Mido
>>>p=partial(someparty,"Ahmed")
>>>p("Mido")
Visitors:
Ahmed
Mido
>>>p
<functools.partialobjectat0xb79d8d74>
>>>p("Mido","Youssef")
Visitors:
Ahmed
Mido
Youssef
- PyQt4
slot connect
self.connect(btn, SIGNAL("clicked()"),
partial(self.onClicked, ARG))
! lambda
self.anyButton - slot button2 clicked
-slot
itertools
)any(iterable
list 3
printany(x>3forxin[1,3,4,5,6,7])#True
)all(iterable
list 3
printall(x>3forxin[1,3,4,5,6,7])#False
list True/False
iterable listcomprehension
LC
)repeat(obj,times=None
iterator times None
))>>>list(repeat(10,3
][10,10,10
)takewhile(pred,seq
seq pred
))]>>>list(takewhile(lambdax:x<3,[0,1,2,3,4
][0, 1, 2
dropwhile(pred,seq)
pred seq
>>>list(dropwhile(lambdax:x<3,[0,1,2,3,4,6,7]))
[3,4,6,7]
groupby(seq[,key=None])
keyfunction seq
-lambdax:x - key
>>>list(groupby("111122233344"))
[('1',<itertools._grouperobjectat0xb77ef36c>),('2',<itertools._grouperobjectat0xb77ef3ec>),('3',
<itertools._grouperobjectat0xb77ef40c>),('4',<itertools._grouperobjectat0xb77ef42c>)]
print[list(i)for(x,i)initertools.groupby("111122233344")]
[['1', '1', '1', '1'], ['2', '2', '2'], ['3', '3', '3'], ['4', '4']]
( iterator groupby
x list listI
things=[("animal","bear"),("animal","duck"),("plant","cactus"),("vehicle","speedboat"),
("vehicle","schoolbus")]
forkey,groupingroupby(things,lambdax:x[0]):
forthingingroup:
print"A%sisa%s."%(thing[1],key)
print""
Abearisaanimal.
Aduckisaanimal.
Acactusisaplant.
Aspeedboatisavehicle.
A school bus is a vehicle.
http://stackoverflow.com/questions/773/howdoiusepythonsitertoolsgroupby
chain(*iters)
iterator
iters
>>>forelinchain("Hello","World",range(3)):
...printel
H
e
l
l
o
W
o
r
l
d
0
1
2
ifilter(pred,seq)
pred iterator .. filter
>>>forxinifilter(lambdax:x>3,[3,2,1,9,8]):printx
...
9
8
>>>list(ifilter(lambdax:x>3,[3,2,1,9,8]))
[9,8]
filter=ifilter
>>>filter(lambdax:x>3,[3,2,1,9,8])
[9,8]
iterator ifilter list filter
ifilterfalse(pred,seq)
pred iterator
>>>list(ifilterfalse(lambdax:x>3,[3,2,1,9,8]))
[3,2,1]
izip(*iters)
iterator zip
>>>list(izip("Hell",[1,2,3,4]))
[('H',1),('e',2),('l',3),('l',4)]
>>>zip("Hell",[1,2,3,4])
[('H',1),('e',2),('l',3),('l',4)]
)Chapter16(PyInotify
inotify .
Real-Time indexer
""
Watches
.. Watches inotify watches " mask
"
pyinotify .. inotify
Events
http://seb.dbzteam.org/swp/pages/pyinotify...entsCodes_Class
IN_CREATE IN_DELETE IN_MOVED_FROM IN_MOVED_TO
" " " "
* rec=True
recursive =True
Goingon
* from pyinotify import
pyinotify.WatchManger pyinotify
WatchManager
mask
)(wm=WatchManager
mask=IN_DELETE | IN_CREATE | IN_MOVED_FROM | IN_MOVED_TO #to watch.
.
) inotify (
mask rec=True
p=PDir()
notifier=Notifier(wm, p)
#add a watch..
watch=wm.add_watch("/home/striky/Desktop", mask, rec=True)
notifier.loop()
PDir
PDir
pyinotify.ProcessEvent
class PDir(ProcessEvent):
def my_init(self, **kwargs):
self.mv_cookies={} # {cookie: src}
def process_IN_DELETE(self, event):
print "Remove: %s"%event.pathname
def process_IN_CREATE(self, event):
print "Create: %s"%event.pathname
def process_IN_MOVED_FROM(self, event):
print "Moving FROM: %s"%event.pathname
self.mv_cookies[event.cookie]=event.pathname
def process_IN_MOVED_TO(self, event):
print "Moving TO: %s"%event.pathname
print " WAS MOVED FROM: ", self.mv_cookies[event.cookie]
Event
Event event ..
( Watch Descriptor ) =< wd
=< name
=< pathname
=< dir
wd bitmask =< mask
pyinotify
http://seb.dbzteam.org/swp/pages/pyinotify.html
Chapter17(GUI)
PyGTK
GTK
) ( -- window
gtk -1
importgtk
gtk class -2
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
.show_all
Window components show_all
.init_comp
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
.set_title(new_title)
title
.set_position(pos)
gtk.WIN_POS_CENTER
gtk.WIN_POS_CENTER_ALWAYS
size
gtk.WIN_POS_MOUSE
.set_size_request(h,w)
if __name__=="__main__":
w=Window()
gtk.main()
click me button
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_border_width(20)
self.set_position(gtk.WIN_POS_CENTER)
btn=gtk.Button("Click Me!")
self.add(btn)
button
button = gtk.Button(label=None, stock=None)
border_width
.set_border_width(width)
button
callback
MessageDialog
parent
gtk.DIALOG_MODAL
( )
gtk.DIALOG_DESTROY_WITH_PARENT
parent
gtk.DIALOG_NO_SEPARATOR
buttons
gtk.MESSAGE_INFO
gtk.MESSAGE_WARNING
gtk.MESSAGE_QUESTION
gtk.MESSAGE_ERROR
(:
callback signal
)btn.connect("clicked", self.__on_btn_clicked, None
None callback
?? widget, data
print widget
data callback
><gtk.Button object (GtkButton) at 0xb803f0
None
widget button
data None ..
...
Clicks
button label
button
OOP
) Hbox ( HorizontalBox
) Vbox (VerticalBox
box homogeneous
)vbox=gtk.VBox(False,2
)pack_start(child,expand,fill,padding
widget " !
)pack_end(child,expand,fill,padding
widget Hbox Vbox
:expand
:fill
:padding
-
) gtk.Table( rows, columns, homogeneous
child attachmethod
.attach( child, left_attach, right_attach, top_attach, bottom_attach,
)xoptions, yoptions, xpadding, ypadding
:child
: left_attach
:right_attach
:top_attach
:bottom_attach
widget 2X2
1 2 right_attach,left_attach
1 2 top_attach,bottom_attach
:xoptions x
:gtk.FILL
: gtk.EXPAND window
:gtk.SHRINK " "
:yoptions y x
:xpadding x
:ypadding y
attach_defaults
attach_defaults( child, left_attach, right_attach, top_attach,
) bottom_attach
left,right,top,bottomattach x,yoptions
gtk.FILL|gtk.EXPAND
x,ypadding 0
fixed fixed "
"
clicks
Vbox
button label
__ clicks
class Window(gtk.Window):
def __init__(self):
)super(Window, self).__init__(gtk.WINDOW_TOPLEVEL
)(self.__init_comp
self.__clicks=0
self.show_all()
def getClicks(self):
return self.__clicks
def setClicks(self, value):
self.__clicks = value
def delClicks(self):
del self.__clicks
clicks = property(getClicks, setClicks, delClicks, "Clicks's
Docstring")
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
title,position,border_width
mvbox=gtk.VBox(False, 0)
button,label VerticalBox
btnclicks=gtk.Button("Click Me!")
lbl=gtk.Label("Clicks: ")
!ClickMe Button
:Clicks Label
self.add(mvbox)
None)
mvbox btnclicks,lbl
window mvbox
__on_btnclicks_clicked
btnclicks clickedsignal
.set_text(newtext)
GObject
|
GtkObject
+GtkWidget
| +GtkMisc
| | +GtkLabel
| | | `GtkAccelLabel
| | +GtkArrow
| | `GtkImage
| +GtkContainer
| | +GtkBin
| | | +GtkAlignment
| | | +GtkFrame
| | | | `GtkAspectFrame
| | | +GtkButton
| | | | +GtkToggleButton
| | | | | `GtkCheckButton
| | | | | `GtkRadioButton
| | | | `GtkOptionMenu
| | | +GtkItem
| | | | +GtkMenuItem
| | | | +GtkCheckMenuItem
| | | | | `GtkRadioMenuItem
| | | | +GtkImageMenuItem
| | | | +GtkSeparatorMenuItem
| | | | `GtkTearoffMenuItem
| | | +GtkWindow
| | | | +GtkDialog
| | | | | +GtkColorSelectionDialog
| | | | | +GtkFileSelection
| | | | | +GtkFontSelectionDialog
| | | | | +GtkInputDialog
| | | | | `GtkMessageDialog
| | | | `GtkPlug
| | | +GtkEventBox
| | | +GtkHandleBox
| | | +GtkScrolledWindow
| | | `GtkViewport
| | +GtkBox
| | | +GtkButtonBox
| | | | +GtkHButtonBox
| | | | `GtkVButtonBox
| | | +GtkVBox
| | | | +GtkColorSelection
| | | | +GtkFontSelection
| | | | `GtkGammaCurve
| | | `GtkHBox
| | | +GtkCombo
| | | `GtkStatusbar
| | +GtkFixed
| | +GtkPaned
| | | +GtkHPaned
| | | `GtkVPaned
| | +GtkLayout
| | +GtkMenuShell
| | | +GtkMenuBar
| | | `GtkMenu
| | +GtkNotebook
| | +GtkSocket
| | +GtkTable
| | +GtkTextView
| | +GtkToolbar
| | `GtkTreeView
| +GtkCalendar
| +GtkDrawingArea
| | `GtkCurve
| +GtkEditable
| | +GtkEntry
| | `GtkSpinButton
| +GtkRuler
| | +GtkHRuler
| | `GtkVRuler
| +GtkRange
| | +GtkScale
| | | +GtkHScale
| | | `GtkVScale
| | `GtkScrollbar
| | +GtkHScrollbar
| | `GtkVScrollbar
| +GtkSeparator
| | +GtkHSeparator
| | `GtkVSeparator
| +GtkInvisible
| +GtkPreview
| `GtkProgressBar
+GtkAdjustment
+GtkCellRenderer
| +GtkCellRendererPixbuf
| +GtkCellRendererText
| +GtkCellRendererToggle
+GtkItemFactory
+GtkTooltips
`GtkTreeViewColumn
ToggleButton
toggle_button=gtk.ToggleButton(label=None)
False True checkbox
False
active
toggled signal
import gtk
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
mvbox=gtk.VBox(False, 0)
togbtn=gtk.ToggleButton("Show Title")
togbtn.set_active(True)
togbtn.connect("toggled", self.__on_toggled)
mvbox.pack_start(togbtn, True, True, 2)
self.add(mvbox)
def __on_toggled(self, widget):
if self.title.strip():
self.set_title(" ")
else:
self.set_title("Hello, World!")
if __name__=="__main__":
w=Window()
gtk.main()
CheckButton
check_button = gtk.CheckButton(label=None)
import gtk
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
mvbox=gtk.VBox(False, 0)
chkbtn=gtk.CheckButton("Show Title")
chkbtn.set_active(True)
chkbtn.connect("toggled", self.__on_toggled)
mvbox.pack_start(chkbtn, True, True, 2)
self.add(mvbox)
def __on_toggled(self, widget):
if self.title.strip():
self.set_title(" ")
else:
self.set_title("Hello, World!")
if __name__=="__main__":
w=Window()
gtk.main()
RadioButton
"Male")
rd2=gtk.RadioButton(rd1, "Female")
rd2.connect("toggled",self.__on_radio_toggled, "Female")
mvbox.pack_start(rd1, False, False, 2)
mvbox.pack_start(rd2, False, False, 2)
) ( Hseparator
mvbox.pack_start(gtk.HSeparator(), True, True, 0)
Adjustment
--
adjustmentobject
Adjustment(value,lower,upper,step_increment,page_increment,page_size)
view model
value
lower
upper
step_increment
Scale
- -
VScale(adjustment)
VScale( min, max, step )
HScale( adjustment );
adjustment
false true set_draw_value draw_value scale
.. true -digits/set_digits
set_value_pos(pos)
value
gtk.POS_LEFT
gtk.POS_RIGHT
gtk.POS_TOP
gtk.POS_BOTTOM
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
adj=gtk.Adjustment(5,1, 101)
hscale=gtk.HScale(adj)
hscale.set_digits(0)
mvbox=gtk.VBox(False, 0)
mvbox.pack_start(hscale, True, True, 0)
mvbox.pack_start(gtk.HSeparator(), True, True, 0)
)self.add(mvbox
update_policy
value adjustment rangewidget value_changedsignal
gtk.UPDATE_CONTINUOUS
range
gtk.UPDATE_DISCONTINUOUS
range
gtk.UPDATE_DELAYED
policy
).set_update_policy(up_policy
adjustment range
get_adjustment.
adjustment
).set_adjustment(adj
scales 2 adjustment
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
adj=gtk.Adjustment(5,1, 101)
hscale=gtk.HScale(adj)
hscale.set_digits(0)
vscale=gtk.VScale(adj)
vscale.set_digits(0)
mvbox=gtk.VBox(False, 0)
mvbox.pack_start(hscale, True, True, 0)
mvbox.pack_start(vscale, True, True, 2)
self.add(mvbox)
.set_digits(num)
(0 )
SpinButton Scale
model ) value adjustmentobject
(Scale,SpinButton
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
adj=gtk.Adjustment(5,1, 101)
hscale=gtk.HScale(adj)
hscale.set_digits(0)
spin=gtk.SpinButton(adj)
spin.set_digits(0)
mvbox=gtk.VBox(False, 0)
mvbox.pack_start(hscale, True, True, 0)
mvbox.pack_start(spin, True, True, 2)
mvbox.pack_start(gtk.HSeparator(), True, True, 0)
self.add(mvbox)
Label/Entry
Label
... Text Entry
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.show_all()
def __init_comp(self):
self.set_title("Hello, World!")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
mvbox=gtk.VBox(False, 0)
lblname=gtk.Label("Name:")
nameentry=gtk.Entry()
hbox=gtk.HBox(False, 0)
hbox.pack_start(lblname, True, True, 0)
hbox.pack_start(nameentry, True, True, 4)
Entry
.set_text(newtext)
.insert_text(text, _from)
.select_region(_from,_to)
.set_max_length(maxlen)
.set_editable(bool)
text
from_ text
to_ from_
entry
Label:
.set_text(text)
.get_text()
.set_justify(just)
JUSTIFY_LEFT
JUSTIFY_RIGHT
JUSTIFY_CENTER
.set_line_wrap(bool)
.set_markup(markup)
gtk.Arrow
text
text
wrap
markup
( )
arrow.set(arrow_type, shadow_type)
arrow_type
ARROW_UP
ARROW_DOWN
ARROW_LEFT
ARROW_RIGHT
shadow shadow_type
SHADOW_IN
SHADOW_OUT
# the default
SHADOW_ETCHED_IN
SHADOW_ETCHED_OUT
class Arrows(object):
def __init__(self):
# Create a new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Arrow Buttons")
# It's a good idea to do this for all windows.
window.connect("destroy", lambda x: gtk.main_quit())
# Sets the border width of the window.
window.set_border_width(10)
# Create a box to hold the arrows/buttons
box = gtk.HBox(False, 0)
box.set_border_width(2)
window.add(box)
# Pack and show all our widgets
box.show()
button = create_arrow_button(gtk.ARROW_UP, gtk.SHADOW_IN)
box.pack_start(button, False, False, 3)
button = create_arrow_button(gtk.ARROW_DOWN, gtk.SHADOW_OUT)
box.pack_start(button, False, False, 3)
button = create_arrow_button(gtk.ARROW_LEFT, gtk.SHADOW_ETCHED_IN)
box.pack_start(button, False, False, 3)
button = create_arrow_button(gtk.ARROW_RIGHT,
gtk.SHADOW_ETCHED_OUT)
box.pack_start(button, False, False, 3)
window.show()
# and pack it into a button
def create_arrow_button(arrow_type, shadow_type):
button = gtk.Button();
arrow = gtk.Arrow(arrow_type, shadow_type);
button.add(arrow)
button.show()
arrow.show()
return button
gtk.Tooltips
( ) tooltip
tooltips = gtk.Tooltips()
set_tip method
tooltips.set_tip(widget, tip_text)
tip widget
tip_text
create_arrow_button
class Tooltips:
def __init__(self):
# Create a new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Tooltips")
# It's a good idea to do this for all windows.
window.connect("destroy", lambda w: gtk.main_quit())
# Sets the border width of the window.
window.set_border_width(10)
# Create a box to hold the arrows/buttons
box = gtk.HBox(False, 0)
box.set_border_width(2)
window.add(box)
# create a tooltips object
self.tooltips = gtk.Tooltips()
# Pack and show all our widgets
box.show()
button = create_arrow_button(gtk.ARROW_UP, gtk.SHADOW_IN)
box.pack_start(button, False, False, 3)
self.tooltips.set_tip(button, "SHADOW_IN")
button = create_arrow_button(gtk.ARROW_DOWN, gtk.SHADOW_OUT)
box.pack_start(button, False, False, 3)
self.tooltips.set_tip(button, "SHADOW_OUT")
button = create_arrow_button(gtk.ARROW_LEFT, gtk.SHADOW_ETCHED_IN)
box.pack_start(button, False, False, 3)
self.tooltips.set_tip(button, "SHADOW_ETCHED_IN")
button = create_arrow_button(gtk.ARROW_RIGHT,
gtk.SHADOW_ETCHED_OUT)
box.pack_start(button, False, False, 3)
self.tooltips.set_tip(button, "SHADOW_ETCHED_OUT")
window.show()
gtk.ProgressBar
progressbar = gtk.ProgressBar(adjustment=None)
adjustment
.set_fraction(fraction)
fraction
.set_orientation(orientation)
PROGRESS_LEFT_TO_RIGHT
PROGRESS_RIGHT_TO_LEFT
PROGRESS_BOTTOM_TO_TOP
PROGRESS_TOP_TO_BOTTOM
.get_text()
progressbar
.set_text(to)
to progressbar
.pulse()
progressbar
def progress_timeout(pbobj):
if pbobj.activity_check.get_active():
pbobj.pbar.pulse()
else:
# Calculate the value of the progress bar using the
# value range set in the adjustment object
new_val = pbobj.pbar.get_fraction() + 0.01
if new_val > 1.0:
new_val = 0.0
# Set the new value
pbobj.pbar.set_fraction(new_val)
# As this is a timeout function, return TRUE so that it
# continues to get called
return True
.activity_check.get_active()
progressobject
PyGWC
class WordCounter(object):
def __init__(self):
pass
def set_file(self, p):
self.filepath=p
fileobj=file(p, "r")
self.txt=fileobj.read()
fileobj.close()
def get_nwords(self):
return self.txt.count(" ")+1
def get_nlines(self):
return self.txt.count("\n")
def get_nchars(self, count_spaces=True):
if count_spaces:
return len(self.txt)
else:
return len(self.txt)-self.get_nwords()
def get_info_as_markup(self, spaces=True):
s="""
<b>Lines:</b> <i>%s</i> line(s).
<b>Words:</b> <i>%s</i> word(s).
<b>Chars:</b> <i>%s</i> char(s).
"""%(self.get_nlines(), self.get_nwords(),
self.get_nchars(spaces))
return s
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__(gtk.WINDOW_TOPLEVEL)
self.__init_comp()
self.wc=WordCounter()
self.show_all()
def __init_comp(self):
self.set_title("PyGWC")
self.set_position(gtk.WIN_POS_CENTER)
self.set_border_width(12)
mvbox=gtk.VBox(False, 0)
btnfile=gtk.Button("File")
btnfile.connect("clicked", self.select_file)
self.fileentry=gtk.Entry()
self.fileentry.set_editable(False)
hbox=gtk.HBox(False, 0)
hbox.pack_start(btnfile, True, True, 2)
hbox.pack_start(self.fileentry, True, True, 1)
mvbox.pack_start(hbox, True, True, 0)
mvbox.pack_start(gtk.HSeparator(), True, True, 2)
self.lblinfo=gtk.Label()
mvbox.pack_start(self.lblinfo, True, True, 0)
self.add(mvbox)
def select_file(self,w):
sel = gtk.FileChooserDialog("Open..",
self,
gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK)
)
sel.set_default_response(gtk.RESPONSE_OK)
))
res=sel.run()
if res==gtk.RESPONSE_OK:
self.wc.set_file(sel.get_filename())
self.fileentry.set_text(sel.get_filename())
self.lblinfo.set_markup(self.wc.get_info_as_markup(spaces=True
else:
print "Dialog with RESPONSE_CANCEL!"
sel.destroy()
) ( FilechooserDialog
constructor
( ACTION_OPEN)
stocks OK,CANCEL
sel = gtk.FileChooserDialog("Open",
self,
gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK)
)
sel WordCounterobject
fileentry
markup wc.get_info_as_markup lblinfo set_markup
method
: ) FileSelection (FileChooserDialog
gtk.ComboBox
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__()
self.__init_comp() #prepare components
self.show_all()
def __init_comp(self):
self.vbox=gtk.VBox(False, 2)
entries = ["Slackware", "Ubuntu", "Mandriva", "Debian"]
cbo=gtk.combo_box_new_text()
map(cbo.append_text, entries)
cbo.connect("changed", self._on_cboselection_changed)
self.vbox.pack_start(cbo, False, False)
self.add(self.vbox)
def _on_cboselection_changed(self, widget, *args):
print widget.get_active_text()
) combo_box_new_text (
append_text entries map
changedsignal _on_cboselection_changed
()get_active_text
Menus
open, 3 File
save, quit
import gtk
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__()
self.__init_comp() #prepare components
self.show_all()
def __init_comp(self):
self.vbox=gtk.VBox(False, 2)
mbar=gtk.MenuBar()
self.vbox.pack_start(mbar, False, False, 2)
mbar.append(file_item)
self.add(self.vbox)
MenuBar -1
mbar=gtk.MenuBar()
self.vbox.pack_start(mbar, False, False, 2)
MenuItem File -2
file_item=gtk.MenuItem("File")
Menu -3
fmenu=gtk.Menu()
-4
file_item.set_submenu(fmenu)
append -5
open_item = gtk.MenuItem("Open")
save_item = gtk.MenuItem("Save")
quit_item = gtk.MenuItem("Quit")
SeparatorMenuItem
callback activatesignal -6
open_item.connect("activate", self._on_item_activated, "Open")
save_item.connect("activate", self._on_item_activated, "Save")
quit_item.connect("activate", self._on_item_activated, "Quit")
def _on_item_activated(self, w, action):
print "Calling %s"%action
-7
)mbar.append(file_item
UIManager
Gladizer
glade
XML glade. gladizer
XML
gladex,glade2py gladizer .
hello.glade glade -1
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
<!--Generated with glade3 3.4.5 on Tue Dec 2 06:07:51 2008 -->
<glade-interface>
<widget class="GtkWindow" id="window1">
<child>
<placeholder/>
</child>
</widget>
</glade-interface>
gladizer
striky@strikydesktop:~/Desktop$gladizer.pyfhello.gladepPython>hello.py
striky@strikydesktop:~/Desktop$pythonhello.py
#!bin/python
##CODEGENERATEDbygladizer1.2
importpygtk
pygtk.require('2.0')
importgtk,gtk.glade
classMainWindow(object):
def__init__(self):
#Widgettree..
self.wTree=gtk.glade.XML('hello.glade')
#connectsignalsandhandlers.
self.wTree.signal_autoconnect(self)
self._window1=self.wTree.get_widget('window1')
self._window1.show()
#runmainloop
defmain():
mainwindow=MainWindow()
#mainwindow.window1.show()
gtk.main()
if__name__=="__main__":
main()
(: callbacks
gladizerguitk gladizer
gladizer
/http://sourceforge.net/projects/gladizer
http://pygtk.org/pygtk2tutorial/index.html
. GTK
RadwithGlade(Gqamoos)
Vbox )( TextEntry,Button
TextEntry
Button
Hbox Entry,Button
TextEntry
General entryKey
Button Entry
Label btnAbout About
signals on_btnAbout_clicked clickedsignal
Expand,Fill Hbox No,No
entryKey on_entryKey_changed changedsignal GtkEditable
TreeView tvResult
gqamoos.py gqamoos.glade gladizer
striky@strikydesktop:~$gladizer.pyfilegqamoos.gladepPython>gqamoos.py
gladizerguitk.py
#!bin/python
##CODE GENERATED by gladizer 1.2
import pygtk
pygtk.require('2.0')
import gtk, gtk.glade
class MainWindow(object):
def __init__(self):
#Widget tree..
self.wTree=gtk.glade.XML('gqamoos.glade')
#connect signals and handlers.
self.wTree.signal_autoconnect(self)
self._window1=self.wTree.get_widget('window1')
self._vbox1=self.wTree.get_widget('vbox1')
self._hbox1=self.wTree.get_widget('hbox1')
self._entryKey=self.wTree.get_widget('entryKey')
self._btnAbout=self.wTree.get_widget('btnAbout')
self._tvResult=self.wTree.get_widget('tvResult')
self._window1.show()
def on_entryKey_changed(self, widget, *args):
pass
def on_btnAbout_clicked(self, widget, *args):
pass
# run main loop
def main():
mainwindow = MainWindow()
#mainwindow.window1.show()
gtk.main()
if __name__ == "__main__":
main()
wordlist lookerservice
importlooker
gobject TYPE_STRING gobject
importgobject
looker.WordListLooker
self._wc=looker.WordsListLooker()
init_tv_ TreeView
self._init_tv()
init_tv_
def _init_tv(self):
encell=gtk.CellRendererText()
encol=gtk.TreeViewColumn("English", encell, text=0)
arcell=gtk.CellRendererText()
arcol=gtk.TreeViewColumn("Arabic", arcell, text=1)
map(self._tvResult.append_column,[encol, arcol])
encol,arcol TreeView
gtk.TreeViewColumn
" " -1
" " encell "" )CellRenderer -2
(
()get_model_ store -3
def _get_model(self):
lstore=gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
self._wc.searchKey=self._entryKey.get_text()
for row in self._wc.lookup():
iter=lstore.append([row[0], row[1]])
return lstore
goject.TYPE_STRING str .
searchKeyproperty get_text entryKey
lookerservice self._wc
store list lstore.append
TreeView model entryKey
on_entryKey_changedcallback
def on_entryKey_changed(self, widget, *args):
self._tvResult.set_model(self._get_model())
TreeView tvResult set_model model
clickedsignal on_btnAbout_clicked
btnAbout
def on_btnAbout_clicked(self, widget, *args):
md=gtk.MessageDialog(self._window1,
gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
"GQamoos: RAD example")
md.set_title("About GQamoos")
md.run()
md.destroy()
.. set_title self._window1
glade
Title window1 Gqamoos
#!bin/python
##CODE GENERATED by gladizer 1.2
import pygtk
pygtk.require('2.0')
import looker
import gobject
import gtk, gtk.glade
class MainWindow(object):
def __init__(self):
#Widget tree..
self.wTree=gtk.glade.XML('gqamoos.glade')
#connect signals and handlers.
self.wTree.signal_autoconnect(self)
self._window1=self.wTree.get_widget('window1')
self._vbox1=self.wTree.get_widget('vbox1')
self._hbox1=self.wTree.get_widget('hbox1')
self._entryKey=self.wTree.get_widget('entryKey')
self._btnAbout=self.wTree.get_widget('btnAbout')
self._tvResult=self.wTree.get_widget('tvResult')
self._window1.show()
self._wc=looker.WordsListLooker()
self._init_tv()
def _init_tv(self):
encell=gtk.CellRendererText()
encol=gtk.TreeViewColumn("English", encell, text=0)
arcell=gtk.CellRendererText()
arcol=gtk.TreeViewColumn("Arabic", arcell, text=1)
map(self._tvResult.append_column,[encol, arcol])
def _get_model(self):
lstore=gtk.ListStore(str, str) #gobject.TYPE_STRING,
gobject.TYPE_STRING
self._wc.searchKey=self._entryKey.get_text()
for row in self._wc.lookup():
iter=lstore.append([row[0], row[1]])
return lstore
def on_entryKey_changed(self, widget, *args):
self._tvResult.set_model(self._get_model())
def on_btnAbout_clicked(self, widget, *args):
md=gtk.MessageDialog(self._window1,
gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
"GQamoos: RAD example")
md.set_title("About GQamoos")
md.run()
md.destroy()
#pass
# run main loop
def main():
mainwindow = MainWindow()
#mainwindow.window1.show()
gtk.main()
if __name__ == "__main__":
main()
HowToGladizerguiTK?
tKInter
( )
entry input
entry output
plugins listbox label
Gladize
-1
fromTkinterimport*
importtkFileDialogastfd
importtkMessageBoxastmd
tkMessageBox tkFileDialog Tkinter
Frameclass
classGladizerWindow(Frame):
def__init__(self,master=None):
Frame.__init__(self,master)
self._inputfile=StringVar()
self._outputfile=StringVar()
self._usedplugin=None
self._init_comps()
init_comps_
get,set
def_init_comps(self):
inp=Button(self,text="Input",command=self._getinputfile)
inp.grid(row=0,sticky=W+N)
self.inpentry=Entry(self,textvariable=self._inputfile)
self.inpentry.grid(row=0,column=1,sticky=E)
out=Button(self,text="Output",command=self._getoutputfile)
out.grid(row=1,sticky=W+N)
self.outentry=Entry(self,textvariable=self._outputfile)
self.outentry.grid(row=1,column=1,sticky=E)
Label(self,text="Plugins:").grid(row=2,column=0,sticky=N+W)
#pluginslist.
self.lbplugins=Listbox(self,height=5,selectmode=BROWSE,relief=SUNKEN)
self.lbplugins.grid(row=2,column=1,columnspan=3,sticky=E+S)
iflen(getplugins())>=1:
forpluginingetplugins():
self.lbplugins.insert(0,plugin)
self.lbplugins.select_set(0)
start=Button(self,text="Gladize!",command=self._gladize).grid(row=3,columnspan=2,sticky=E+S)
self.grid()
Button
inp=Button(self,text="Input",command=self._getinputfile)
text
callback command
column, row grid
columnspan
Entry
self.inpentry=Entry(self,textvariable=self._inputfile)
self._inputfile textvariable
Listbox
self.lbplugins=Listbox(self,height=5,selectmode=BROWSE,relief=SUNKEN)
( . )
self.lbplugins.grid(row=2,column=1,columnspan=3,sticky=E+S)
insert
iflen(getplugins())>=1:
forpluginingetplugins():
self.lbplugins.insert(0,plugin)
select_set
self.lbplugins.select_set(0)
( SUNKEN ) relief
input,output callbacks
def_getinputfile(self,*args):
self._inputfile.set(tfd.askopenfilename())
#self.inpentry.delete(0,END)
#self.inpentry.insert(0,self._inputfile)
def_getoutputfile(self,*args):
self._outputfile.set(tfd.asksaveasfilename())
#self.outentry.delete(0,END)
#self.outentry.insert(0,self._outputfile)
( ) tkFileDialog
)( tfd.askopenfilename
StringVarobject set
()tfd.asksaveasfilename
showerror,showinfo,..etc tkMessageBox
defshowerror(self,msg):
)tmd.showerror("Error",msg
showerror
))(tmd.showinfo("Gladized","%sgladizedsuccessfully!"%self._outputfile.get
showinfo
get StringVar
defmain():
root=Tk()#Master
gw=GladizerWindow(root)#GladizerWindow
root.mainloop()#Enteringthemainloop
if__name__=="__main__":
main()
root=Tk()#Master
gw=GladizerWindow(root)#GladizerWindow
mainloop
root.mainloop()#Enteringthemainloop
* : replacer
Qt
Qt
ZetCode pdf
) Qt/Ruby
( PyQt4
wxPython
) (
tKinter
) HowtoGladizerGUItk
GTK wxPython (Qt
Py3K
Python2.5
http://docs.python.org/3.0/whatsnew/3.0.html
!
!
) ( XML,INI,Databases,..etc
) GTK ( Glade
MonoIronPythonWinFormsTutorial
PyGTKTutorial
- PyQt4 ZetCode PyQt4 .. PyQt4
http://ojuba.org/wiki/doku.php/docs/pyqt4
/http://python.org/doc
LearningPython3rd
ProgrammingPython,3rdEdition
)( LearningPython3rd
tKInter
clientside serverside
CorePythonProgramming,2nd
LearningPython Programming
Python3rd
FoundationsofAgilePythonDevelopment
FoundationsofPythonNetworkProgramming
POP,IMAP,SMTP
WroxBeginningPython
XML Networking
LearningPython
TwistedNetworkProgrammingEssentials
twisted )
( twisted
ManningwxPythoninAction
wxPython wxPython
wxPython
RapidGUIProgrammingwithPythonandQt
1 Python,Qt
QtDesigner
ProgrammingFr34ks
http://programmingfr34ks.net/smf/articles12/
:1 Py2EXE
Py2EXE
(1
http://www.py2exe.org
(2
#!bin/python
"! print "Programming Fr34ks r0x
(3 pf.py
(4
#!bin/python
from distutils.core import setup
import py2exe
#pf.py is our script name
)]'setup(console=['pf.py
(5
%>python setup.py py2exe
(6 dist
(7
%>pf.exe
! Programming Fr34ks r0x
:2/ /
VIM
UNIXLIKE ) (
)http://en.wikipedia.org/wiki/Vim_(text_editor
vimtutor vim vim
http://www.swaroopch.com/notes/Vim
)Gedit(GnomeEditor
Gnome
pida
pygtk vim emacs
RegexToolkit
http://pida.co.uk/screenshots :
)Kate(KDEAdvancedEditor
KDE
Komodo
IDE
)OpenKomodo(KomodoEdit
Komodo
PyDev
http://pydev.sourceforge.net/
.. quickfixes refractoring
Glade
GTK Gqamoos
Geany
/http://www.geany.org :
Gazpacho
http://gazpacho.sicem.biz/
gtk glade
wxGlade
http://wxglade.sourceforge.net/
wx Glade
BoaConstructor
http://boaconstructor.sourceforge.net/
.. ( ) IDE
IronPython Studio
-1
-2
-3
-4
Py3k :3
Todo