You are on page 1of 12

6.

5 python

English

6.5 python


6.5.1
6.5.2
6.5.3
6.5.4
6.5.5
6.5.6
6.5.7 modules/packages
6.5.8

6.5.1
) python ( . byte code
OOP *redhat-config-
}{

LinuxToday
Linux.org
Linux.com
SlashDot
FreshMeat
LWN.net

) (

.
#!/usr/bin/python
# hello.py - My 1st python application
"!!print "Hello World

"" script # ;
. \ .

:


:
: ) (

#!/usr/bin/python Ubuntu
# quoting.py - quoted strings in python
" print "you can put ' in side double quotes without a escape . .
"print "you can't put \" in side double quotes without a escape

'print 'you can put " in side single quotes without a escape
'print 'you can\'t put \' in side single quotes without a escape
:
# \X1b ,\x1b, \X1B or \x1B (hex for ESC) and \033 for oct ESC
" print "Visit us on \033[34,4mwww.daif.net/linux\033[0m
'print 'Do \033[1mNOT\033[0m ignore \033[5mme\033[0m.
:
# put r or R in front of a quote to make it raw
# in such case \n mean \n not new line
'"print 'backslashs need to be esaped like "C:\\windows\\fonts

'"print r'backslashs need NOT to be esaped in raw quotes like "C:\windows\fonts


two adjacent strings are like if they are one string
#print
"? "what " "is " "your name
print ''' W E L C O M E
T O
3 Q U O T E S
This type of quoting allow you to put " and ' or even "" without :
it can be a multi-line string without puting escaped

//:http escaping,
'''newlines, it's very usefull for CGI too.
print """ W E L C O M E
T O
3 D O U B L E Q U O T E S
"""Same as the previous but with double quotes

Python integers
long-integers ) ( - ) ( x 27 0x1B
033 long ) (bc L
l .0xFFFFFFFEl ) ( 27.
e 0.3e+9 0.3x10+9 )( J
j 0.3+1.9j


string conv ltr
dictionary ltr
converted by Web2PDFConvert.com

Web

www.cltb.net

Google


Django Developer

``
}{

www.allengeer.com
Expert Django Developer Allen Geer,
Software Engineer

[]

list
tuple
functions call
slicing
subscript access
member access


( )



''
) (

()
()
[:]

[ ]
.
**
~
+ * / %
+ << >>
&
^


Generously Hosted by
www.JadMadi.net

| ^
< > <= >=
== !=
is ,is not
in ,not in
not
and
or
lambda

ltr
ltr
ltr
ltr
ltr
ltr
rtl
ltr
rtl
ltr
ltr
ltr
ltr
ltr
ltr

ltr




lembda ( define/inline )

ltr
ltr
ltr
ltr
ltr

myfoo(x,y): x+y ltr


perl printf print print print

#!/usr/bin/python
# print.py - some print tricks
print "Hello ",
print "World!!"
# print can do printf just put %
print "look %8.3f" % 15.

) ( $
. float int
#!/usr/bin/python
# var1.py - how to use variables
msg1 = "Hi! How are you today?"
print "/\" * 10
print msg1
print "\/" * 10
i = int(10.5)
j = int("3")
k = i/j
print "i = ", i, ",j = ", j, ",k = ", k
a = float(10.5)
b = float("3")
c = a/b
print "a = ", a, ",b = ", b, ",c = ", c

. raw_input
#!/usr/bin/python
# user-input.py - how to get input from the user.
nm=raw_input("Enter your name: ")
print "Hi", nm
i=int(raw_input("Enter an integer: "))
j=int(raw_input("Enter an integer: "))
print " i + j =",i+j
print " i - j =",i-j
print " i * j =",i*j
try:
print " i / j =",i/j
except:
print "Can't divide by zero!!"
print "nice to meet you ",nm
converted by Web2PDFConvert.com

except ) ( try Python


raise .[ EXCEPTIONS]...

.[ EXCEPTIONS]...
#!/usr/bin/python
# python and exception handling
x=10
try:
v=float( raw_input("Enter the speed: ") )
except:
print "Error , you should enter a float number"
print v
try:
print x/v
except ZeroDivisionError:
print "Error , can't divide by zero"

Python Tutorial td python cheatsheet Python Quick Reference


html python

6.5.2
TAB : python block }{
elif : ) ( if if .
else
#!/usr/bin/python
# if1.py - simple if
i=int(raw_input("Enter an integer: "))
# if the remainder is not zero then it's odd
if (i % 2):
print i," is odd"
else:
print i," is even"

#!/usr/bin/python
# if2.py - more about if
i=int(raw_input("Enter an integer less than 4 : "))
if (i == 1):
print "one"
elif (i == 2):
print "two"
elif (i == 3):
print "tree"
else:
print i," is NOT less than 4"

for-in
#!/usr/bin/python
for i in (0,1,2,3,4,5):
print i
for i in range(5):
print i

while
#!/usr/bin/python
i=1
while (i<=10):
print i; ++i

else python continue break


) break
.(
return def
#!/usr/bin/python
# gcd0.py - simple buggy gcd calc
def gcd(x,y):
d=min(x,y)
converted by Web2PDFConvert.com

while (d>=1):
if ( x % d) == (y % d) == 0 :
return d
else:
d-=1
a=int( raw_input("Enter a +ve integer: ") )
b=int( raw_input("Enter a +ve integer: ") )
print "The greatest common divisor is", \
gcd(a,b)

euler
. =
#!/usr/bin/python
# default-arg.py - how to give an argument a default value
def test(a="Hello",b="world"):
print a,", ",b,"!!"
test("Hi","Ahmad")
test()
test(b="Ahmad")

6.5.3
Tuple List 3 Sequence array
String
. [ ] . 2-
:
#!/usr/bin/python
# a is an array
a=[1,2,3,4,5]
# you may say a=(1,2,3,4,5) or a=1,2,3,4,5
print "a = ",a
print "the 1st one is ",a[0]
print "the last one is ",a[-1]
print "the 2nd to 4th elements are ",a[1:3]
print "from the 2nd ",a[1:]
print "to the 4th ",a[:3]
print "a = ",a[:]
# strings are array
s="Amman"
print "Am[man] : ",s[2:]

max min len


#!/usr/bin/python
# mean.py - calculate the mean of integers
a=[]
while (1):
i=int( raw_input("Enter an integer (-1 to exit): ") )
if (i==-1):
break
a.append(i)
print "you entered : ",a
print " max=",max(a),
print " mix=",min(a)
s=0
for i in a:
s+=i
print " sum=",s,
print " sum=",float(s)/len(a)

append
LIST.[i:j]=LIST2
LIST2 LIST j i /
LIST.append(X)
LIST X
LIST
.extend(LIST2)
LIST LIST2
I LIST LIST2 LIST.insert(I,LIST2)
LIST.index(X)
LIST X
LIST.count(X)
LIST X
del LIST.[i:j]
LIST j i
converted by Web2PDFConvert.com

)]LIST.pop([I
I LIST
)LIST.remove(X
X LIST
)(LIST.reverse

LIST FUNC 1- 0 1
)]LIST.sort([FUNC

tuple ) (
#!/usr/bin/python
# A tuple is a const array you can only add
)aTuple=(3.0,"two",1
]print "the second is", aTuple[1
)aTuple+=(0,
print "it's now", aTuple

arrays
. }{ :
}"dict1={1 : "first","two" : "second

hash
)# A dictionary is a hash (array accessed by a key
}"aDict={"key1":"val1","key2":"val2","key3":"val3
for item in aDict.keys():
print aDict[item], # to keep in the same line
print # to end the line

methods
)len(DICT
DICT
del
]DICT[KEY
KEY DICT
)(DICT.clear

)(DICT.value
DICT
)(DICT.items
DICT )(KEY,VALUE
)(DICT.keys
DICT
DICT
(.has_key
)KEY
KEY

6.5.4
Python string module import string

)(STR.upper

)(STR.lower

)(STR.swapcase

)(STR.title

)(STR.capitalize

)(STR.strip
)(STR.lstrip
)(STR.rstrip
)]STR.expandtabs([TABSIZE
)STR.ljust(W
)STR.rjust(W
)STR.center(W

TAB STR
TAB STR
TAB STR
TAB STR TABSIZE
STR W
STR W
STR W

)]]STR.count(SUB[,START[,END
)]]STR.find(SUB[,START[,END
)]]STR.index(SUB[,START[,END
)]]STR.rfind(SUB[,START[,END
)]]STR.rindex(SUB[,START[,END
)]STR.replace(OLD,NEW[, MAX
)(STR.isalnum
)(STR.isalpha
)(STR.digit
converted by Web2PDFConvert.com

SUB STR
SUB STR ) 1- (
SUB STR try
find
index
OLD NEW
STR
STR
STR

STR.islower()
STR
STR.isupper()
STR
STR.istitle()
STR
STR.isspace()
STR
PREFIX STR STR.startswith(PREFIX[,START[,END]])
STR.endswith(SUFFIX[,START[,END]])
SUFFIX STR
STR.split([SEP[,MAX]])
SEP STR
STR.splitlines([keepends])
STR
STR.join(SEQ)
STR SEQ split
STR.encode([ENCODING[,ERRORS]])
ENCODING
STR.translate(TABLE[,DELCHARS])
STR TABLE
perl printf %
a="you have %05d trials." % 15
print a

. import re . RE python
: .

RE
re.escape(STR)
\ STR escape
re.S re.M re.L re.I 0 FLAGS PAT re.compile(PAT[,FLAGS=0])
| re.X
STR PAT re.match(PAT,STR[,FLAGS])

STR PAT

NEW .STR NEW PAT

.

re.search(PAT,
STR[,FLAGS])
re.findall(PAT,STR)
re.sub(PAT,NEW,
STR[,COUNT=0])
re.subn(PAT,NEW,
STR[,COUNT=0])

.PAT STR re.split(PAT,STR[,MAX=0])


. compile
CPAT.match(STR[,POS][,ENDPOS])
CPAT.search(STR[,POS][,ENDPOS])
CPAT.findall(STR)
CPAT.sub(NEW, STR[,COUNT=0])
CPAT.subn(NEW, STR[,COUNT=0])
CPAT.split(STR[,MAX=0])

)( match
pos
index
endpos
. index
re

string


#!/usr/bin/python
# python and RE's
import re
str1="This is a string and it's a good string"
myre1=re.compile(r"^This") # a line starts with "This"
myre2=re.compile(r"\b\w*ood\b") # a word end's with ood
myre3=re.compile(r"\bt\w*\b,",re.I) # a word start's with t or T (case insensitive)
if (myre1.search(str1)):
print "RE 1 ws found"
if (myre2.match(str1)):
print "RE 2 ws found"
if (myre3.match(str1)):
print "RE 3 ws found"
r=myre3.findall(str1)
print "number of RE 3 matches is ", len(r)
print "and they are"
for i in r
print i,

converted by Web2PDFConvert.com

print


\A
\b .
\B
\d ].[0-9
\D ].[^0-9
\s ].[ \t\n\r\f\v
\S ].[^ \t\n\r\f\v
\w ) (
\W .
\Z .

6.5.5

FILENAME
)eval(STR
STR ("eval("1+2 3
PROMPT .
)] input([PROMPT
)]raw_input([PROMPT
.
)]] range(START [,END[,STEP START END STEP
)execfile(FILENAME

xrange(START
)]][,END[,STEP
slice([START,] END
)][,STEP
xrange(START
)]][,END[,STEP
)reduce(FUNC ,LIST
)len(OBJ
)max(LIST )min(LIST
)cmp(X,Y
)abs(X
)round(X,N=0
)]pow(X,Y [,Z

START END STEP


! ?slice START END STEP
START END STEP
FUNC LIST
OBJ
LIST
1- 0 1 X-Y
X
X N
X Y Z

)div(X,Y

X/Y

)chr(N

N
C .
OBJ
OBJ
OBJ
OBJ float
X
X -
X+Yj
SEQ
SEQ tuple .
SEQ FUNC

)ord(C
)str(OBJ
)int(OBJ
)long(OBJ
)float(OBJ
)oct(X
)hex(X
)complex(X,Y
)list(SEQ
)tuple(SEQ
)filter(FUNC,SEQ

6.5.6
) ( )]' open([FILENAME [,MODE='r FILENAME
MODE ) (
print [>> FILEOBJ,] [STR1 [,

]STR2 ]... [,
)]F.read([SIZE
)(F.readline
)F.write(STR
)(F.readlines
)F.writelines(LIST
converted by Web2PDFConvert.com

) F (
SIZE ) (

STR

LIST

)]F.seek(OFFSET[,WHENCE=0
)(F.tell
)(F.flush
)(F.close
)(F.fileno
)(F.isatty

OFFSET
WHENCE 0 1 2 .

buffer

fd os
TTY

6.5.7 modules/packages
import MODULE
(dir(MODULE .string .

sys
[sys.argv[0
sys.argv
.
)sys.exit(N=0

sys.exitfunc

sys.platform
)( os.name
sys.maxint

) sys.setdefaultencodin(ENCODING ENCODING
sys.getrecursionlimit

)sys.setrecursionlimit(N

os
os.name
os.error
os.curdir
os.pardir
os.sep
os.sep
os.linsep
os.environ



- "".
- ""..
- "\\" ""/
- PATH ";" "":
- "\ "r\n "\"n
- PATH
]"os.environ["PATH

os
)] os.mkdir(PATH[,MODE
)]os.makedirs(PATH,[MODE=0777

PATH MODE

) os.rmdir(PATH
)os.removedirs(PATH

PATH

) os.unlink(PATH
)os.remove(PATH
)os.rename(OLDNAME,NEWNAME
)( os.getcwd )os.chdir(PATH
)os.listdir(PATH
)os.chmod(PATH,MODE
)os.stat(PATH
) )os.utime(PATH, (A,M
)(os.times
)os.open(FILE,FLAG, MODE
)os.read(FD, N
)os.write(FD, STR
)os.lseek(FD, POS,WHENCE
)os.close(FD
)os._exit(N
)os.execv(PATH, ARGV
)os.system(COMMAND
)(os.pipe
)(os.fork

converted by Web2PDFConvert.com

) PATH (
/ OLDNAME NEWNAME shutil
) pwd cd (
PATH
PATH
PATH st_size st_atime st_mtime
st_ctime st_ino st_uid st_gid
PATH A M
time
fd
FD N
STR FD
FD POS WHENCE 0 1 2

- - sys.exit
PATH ARGV . fork
COMMAND shell
- r w
/

)]'os.popen(COMMAND,[MODE='r
)(os.getpid
)(os.wait
)os.waitpid(PID,OPTIONS
)os.kill(PID,SIGNAL

COMMAND shell


PID
kill

path os
)os.path.dirname(PATH
)os.path.basename(PATH
)os.path.split(PATH
)os.path.splitext(PATH
)os.path.abspath(PATH
)os.path.expanduser(PATH
)os.path.expandvars(PATH
)os.path.exists(PATH
)os.path.isabs(PATH
)os.path.isdir(PATH
)os.path.islink(PATH
)os.path.ismount(PATH
)]]os.path.join(P1[,P2[,...
)os.path.getsize(FILENAME
)os.path.getmtime(FILENAME
)os.path.getatime(FILENAME

PATH
PATH
PATH
PATH
PATH ""..
"~" PATH
" "$VAR PATH
PATH
PATH
PATH/
PATH
PATH
P1 .. P2 ) os.sep(
FILENAME
FILENAME 1970
FILENAME 1970

shutil
)shutil.copy(SRC, DEST
shutil.copytree(SRC, DEST[,
)]SYMS
)shutil.rmtree(PATH

SRC ) DEST (
SRC DEST SYMS

PATH

time
)time.sleep(SEC

SEC
1970 UTC/GMT
SEC .

) time.gmtime(SEC
)time.localtime(SEC

(year aaaa, month(1-12),day(1-31), hour(0-23),


minute(0-59), second(0-59), weekday(0-6, 0 is
monday), Julian day(1-366), daylight flag(-1,0 or
))1

)time.asctime(TM
)time.strftime(FMT,TM

TM FMT

)]time.strptime(STR[,FMT

TM
STR FMT localtime

)(time.time

)time.mktime(TM

math
math.pi
""
math.e

euler 2.71828183
)math.fabs(X


(math.floor(X )math.ceil(X
)math.fmod(X, Y
X/Y
)math.modf(X
X
+9
) math.frexp(X ) math.ldexp(X, Y 0.3x10

) math.sin(X )math.asin(X

) math.cos(X )math.acos(X
) math.tan(X ) math.atan(X
X/Y
)math.atan2(X, Y

) math.sinh(X ) math.cosh(X
)math.tanh(X
)math.exp(X
) math.log(X )math.log10(X
) math.pow(X, Y )math.sqrt(X

converted by Web2PDFConvert.com

hyperbolic
euler X
10
X Y X

6.5.8
class
class MyClass [(MyClassBase1 , MyClassBase2... )]:

self . / MyClassBase1 MyClass


member variables .__del__ __ init__ .++* this
self.X
MODULE import MODULE
... .py
__ name__
if __name__ == "__main__":
print """
Hello, I'm a lib used by other programs
don't runme
"""

#!/usr/bin/python
# this is SimpleClass.py
# OOP and classes
class Simple:
# the self arg is just like this (you can't delete it)
def __init__(self, str):
print "Inside the Simple constructor"
self.s = str
# Two methods:
def show(self):
print self.s
def showMsg(self, msg):
print msg + ':',
self.show() # Calling another method
# if we are runed as a prog (else then this file is used as module)
if __name__ == "__main__":
# Create an object:
x = Simple("constructor argument")
x.show()
x.showMsg("A message")

#!/usr/bin/python
# Inheritance
# search for SimpleClass.py and import it
from SimpleClass import Simple
class Simple2(Simple):
def __init__(self, str):
print "Inside Simple2 constructor"
# You must explicitly call
# the base-class constructor:
Simple.__init__(self, str)
def display(self):
self.showMsg("Called from display()")
# Overriding a base-class method
def show(self):
print "Overridden show() method"
# Calling a base-class method from inside
# the overridden method:
Simple.show(self)
class Different:
def show(self):
print "Not derived from Simple"
if __name__ == "__main__":
x = Simple2("Simple2 constructor argument")
x.display()
x.show()
x.showMsg("Inside main")
def f(obj): obj.show() # One-line definition
f(x)
f(Different())

converted by Web2PDFConvert.com

#!/usr/bin/python
# i18n with python
os.environ.get("LC_LOCAL")
import gettext
gettext.bindtextdomain ("myprog", "/usr/share/locale")
gettext.textdomain ("myprog")
_=gettext.gettext
# any thing to be translated passed to _( )
print _("Hello I'll be translated")
PYTHONPATH="./" gtk- PYTHONPATH
: test.py
import sys
import os
sys.path.append(os.path.dirname(sys.argv[0]))
# or
# sys.environ["PYTHONPATH"]=os.path.dirname(sys.argv[0])

import gtk
#!/usr/bin/python
# gtk-test.py: simple gtk2 example
import gtk
def hello_cb(button):
print "Hello World"
window.destroy()
window = gtk.Window(gtk.WINDOW_TOPLEVEL) # create a top level window
window.connect("destroy", gtk.mainquit) # quit the event loop on destruction
window.set_border_width(10)
# set padding round child widget
button = gtk.Button("Hello World")
button.connect("clicked", hello_cb)
window.add(button)
button.show()

# call hello_cb when clicked


# add button to window
# show button

window.show()
gtk.main()

# enter the main event loop

: glade GTK 8.3


#!/usr/bin/python
import sys
import gtk
def quit(*args):
gtk.main_quit()
def findsum(*args):
x=float(entry1.get_text())
y=float(entry2.get_text())
z=x+y
entry3.set_text(str(z))
win = gtk.Window()
table=gtk.Table(4,2)
label1=gtk.Label('First number: '); entry1=gtk.Entry();
label2=gtk.Label('Second number: '); entry2=gtk.Entry();
label3=gtk.Label('Summation : '); entry3=gtk.Entry()
ok = gtk.Button(stock='gtk-ok');
cancel = gtk.Button(stock='gtk-cancel');
win.add(table)
table.attach(label1,0,1,0,1,gtk.FILL); table.attach(entry1,1,2,0,1,gtk.FILL);
table.attach(label2,0,1,1,2,gtk.FILL); table.attach(entry2,1,2,1,2,gtk.FILL);
table.attach(label3,0,1,2,3,gtk.FILL); table.attach(entry3,1,2,2,3,gtk.FILL);
table.attach( ok ,0,1,3,4); table.attach(cancel,1,2,3,4);
entry1.set_editable(gtk.TRUE)
entry2.set_editable(gtk.TRUE)
entry3.set_editable(gtk.FALSE)
# another method entry1.set_property('editable',gtk.FALSE)
ok.connect('clicked', findsum)
cancel.connect('clicked', quit)
win.connect('destroy', quit)
win.show_all()
gtk.main()

glade
converted by Web2PDFConvert.com

import gtk
import gtk.glade
def some_handler(widget):
pass
xml = gtk.glade.XML('filename.glade')
widget = xml.get_widget('widgetname')
xml.autoconnect({
'some_handler': some_handler
})
gtk.main()

: CGI python
#!/usr/bin/python
# python and CGI
import cgi
print """
<html>
<body>
<h1>Hello world</h1>
</body>
</html>
"""

help python python


.( help(gtk.Toolbar import gtk
www.python.org
www.python.sf.net
www.starship.python.net
www.vex.net/parnassus
www.zope.com
www.pythonware.com
www.devshed.com
www.mindview.net/Books/TIPython
members.nbci.com/alan_gauld/tutor/tutindex.htm
aspn.activestate.com/ASPN/Python/cookbook
www.networkcomputing.com/unixworld/tutorial/005/005.html
www.vic.auug.org.au/auugvic/av_paper_python.html

python 6.5
Copyright 2007, Muayyad Saleh AlSadi

converted by Web2PDFConvert.com

You might also like