1 An Introduction to python, Harrison B. Prosper, 1997 An Introduction to Python Harrison B. Prosper...
-
Upload
jemimah-carpenter -
Category
Documents
-
view
224 -
download
1
Transcript of 1 An Introduction to python, Harrison B. Prosper, 1997 An Introduction to Python Harrison B. Prosper...
An Introduction to python, Harrison
B. Prosper, 1997
1
An Introduction toAn Introduction to
PythonPythonAn Introduction toAn Introduction to
PythonPythonHarrison B. ProsperFlorida State University
An Introduction to python, Harrison
B. Prosper, 1997
2
AcknowledgementsAcknowledgementsAcknowledgementsAcknowledgements
I learnt a great deal by browsing the python web site and its linked pages. http://www.python.org http://www.python.org/doc/tut/tut.html
Guido van Rossum (python author) David Beazley (SWIG author, University of Utah) Mark Lutz’s excellent book.
Programming Python, O’Reilly Associates Inc. Frederick Lundh’s Tkinter documentation is very helpful.
http://www.pythonware.com/library.htm
An Introduction to python, Harrison
B. Prosper, 1997
3
OutlineOutlineOutlineOutline
Part I What is python? Getting started Namespaces Sequences Functions Classes Odds and ends
Part 2 Graphical User Interfaces A Simple GIF/JPEG/BMP Browser
An Introduction to python, Harrison
B. Prosper, 1997
4
What is python?What is python?What is python?What is python?
Python is a scripting language, created by Guido van Rossum ([email protected]), that is: interpreted object-oriented dynamically typed simple powerful and free
Python website: http://www.python.org
An Introduction to python, Harrison
B. Prosper, 1997
5
Getting startedGetting startedGetting startedGetting started
The python interpreter has been ported to all the popular platforms, including Windows 95/NT.
Running python interactively: setup python python >>> print ‘Thou lump of foul deformity’ Thou lump of foul deformity >>> x = 2; y = 5 >>> z = x*y >>> z 10
An Introduction to python, Harrison
B. Prosper, 1997
6
Example 1 (from, import, for, in, if, else)Example 1 (from, import, for, in, if, else)Example 1 (from, import, for, in, if, else)Example 1 (from, import, for, in, if, else)
from string import atoi, split # Add atoi, split to global namespace.import os # Add os to global namespace.f = os.popen(‘cd; ls -l’) # Pipe command output to file.s = f.read() # Read into a single string. l = split(s,’\n’) # Split into a list of strings.n = len(l) # Get length of list.for j in xrange(n): # Iterate over a range object.
a = split(l[j]) # Split into a list of strings.if (len(a) > 4): # If length of list > 4 convert
size = atoi(a[4]) # string value into an integer.print size, l[j]
else: LOOK MA, NO BRACES BECAUSEprint l[j] PYTHON USES INDENTATION!
An Introduction to python, Harrison
B. Prosper, 1997
7
NamespacesNamespacesNamespacesNamespaces
__builtins__
Global (import)
osos __builtins____builtins__
f, s, atoi, splitl, n, j, a, size
len, xrange, dir, open,...
popen, system,listdir, environ,path,...
An Introduction to python, Harrison
B. Prosper, 1997
8
Looking at namespacesLooking at namespacesLooking at namespacesLooking at namespaces
l = dir() Create a list of the namesfor j in xrange(len(l)): in the global namespace
print l[j]
l = dir(__builtins__) Create a list of the namesin the namespace of the module__builtins__
l = dir(os) Do likewise for the module os
An Introduction to python, Harrison
B. Prosper, 1997
9
Example 2 (map, lambda)Example 2 (map, lambda)Example 2 (map, lambda)Example 2 (map, lambda)
l = dir(__builtins__) # List names in module __builtins__o= map(lambda x: x+`\n’,l) # For every element x of list apply the
# one-line function f(x) = x+`\n’ and# return the result in the list o.
f = open(‘builtins.txt’,’w’) # Open a file object f for output.f.writelines(o) # Write out list of newline-terminated
# strings. f.close() # Close file object.
from string import strip # Add strip to global namespace.g = open(‘builtins.txt’,’r’) # Open file for input.t = g.readlines() # Read entire file into list t.t = map(strip,t) # Strip off whitespace (here newline).
An Introduction to python, Harrison
B. Prosper, 1997
10
Example 3 (filter)Example 3 (filter)Example 3 (filter)Example 3 (filter)
from string import strip, find # Import strip and findt = open(‘builtins.txt’).readlines() # Read entire file into list t.t = map(strip,t) # Strip off whitespace.
o = filter(lambda x: find(x,`Error’) > 0, t) # For every x in list t# apply the one-line function # f(x) = find(x,’Error’) > 0# If f(x) is true (i.e., f(x)=1) # copy x to output list o.
# Example of python error code: AttributeError
An Introduction to python, Harrison
B. Prosper, 1997
11
Sequence typesSequence typesSequence typesSequence types
Immutable types (can’t be changed) Strings aString = ‘Go boil your head’ Tuples aTuple = (‘Bozo’,42,3.14,aString)
Mutable types (can be changed) Lists aList = [aString, aTuple,1997] Dictionaries aMap = {‘string’:aString,(1,2):aList}
General operators on sequence s len(s), min(s), max(s), s[i], s[i:j] (= s[i]..s[j-1]) x [not] in s 1 if item x [not] in s, else 0 s + t concatenate sequences s and t n*s n copies, concatenated
An Introduction to python, Harrison
B. Prosper, 1997
12
Tuples (immutable; can’t be changed)Tuples (immutable; can’t be changed)Tuples (immutable; can’t be changed)Tuples (immutable; can’t be changed)
0 1 2 3 4 5>>> IamAtuple = (‘The’,’time’,3.141,’has’,42,’come’)>>> IamAtuple[0]; IamAtuple[5]‘The’‘come’
>>> IamAtupleSlice = IamAtuple[3:6]>>> IamAtupleSlice(‘has’,42,’come’)
>>> IamAtupleCopy = IamAtuple[:]>>> len(IamAtupleCopy)6
An Introduction to python, Harrison
B. Prosper, 1997
13
Lists (mutable; can be changed)Lists (mutable; can be changed)Lists (mutable; can be changed)Lists (mutable; can be changed)
>>> IamAlist = [‘The’,’time’,3.141,’has’,42,’come’]>>> IamAlist[0]‘The’
>>> IamAlist[2] = (1,2,3); IamAlist[‘The’,’time’,(1,2,3),’has’,42,’come’]
>>> IamAlist.sort()[42,’The’,’come’,’has’,’time’,(1,2,3)]
>>> IamAlist.append(1997); IamAlist[42,’The’,’come’,’has’,’time’,(1,2,3),1997]
An Introduction to python, Harrison
B. Prosper, 1997
14
Dictionaries, or mappings (mutable)Dictionaries, or mappings (mutable)Dictionaries, or mappings (mutable)Dictionaries, or mappings (mutable)
>>> IamAmap = {} # An empty dictionary>>> IamAmapAlso = {1:’one’,(2,’boo’):’two’}
>>> IamAmap[‘language’] = (‘python’,1997) # Bind keys to>>> IamAmap[‘comment’] = ‘Superb!’ # values.>>> IamAmap[‘cost’] = 0>>> IamAmap[‘map’] = IamAmapAlso
>>> IamAmap.keys() # Get list of keys[‘cost’,’language’,’comment’,’map’]
>>> IamAmap.values() # Get list of values[0,(‘python’,1997),’Superb!’,{1:’one’,(2,’boo’):’two’}]
An Introduction to python, Harrison
B. Prosper, 1997
15
Functions (def, None, return)Functions (def, None, return)Functions (def, None, return)Functions (def, None, return)
def goofy(a, b=‘yahoo’,*t, **k): # a is a required arg.# b is a req. arg. with a default.# *t, **k are optional args.
r1 = r2 = None # None is a python object.if ( len(t) > 0 ): # *t is a tuple of args.
r1 = t[0] # **k is a set of keyword args.if ( k.has_key(‘title’) ): # Check if key ‘title’ exists.
r2 = k[‘title’] # Get value for given key.return (r1,r2) # Return as a tuple.
>>> a, b = goofy(1,’sucks’,1,2, title=‘2001’,author=’Clarke’)>>> print a, b1 2001
An Introduction to python, Harrison
B. Prosper, 1997
16
ClassesClassesClassesClasses
class FourVector: # Name of class
def __init__(self, px=0,py=0,pz=0,E=0): # Constructorself.ok = 1 # Creation okif E >= 0:
self.px, self.py, self.pz, self.e = px,py,pz,Eelse:
self.ok = 0 # Creation failed
def __del__(self): # Destructorpass
>>> p = FourVector(12,-14,13,80)
An Introduction to python, Harrison
B. Prosper, 1997
17
Classes, __str__ methodClasses, __str__ methodClasses, __str__ methodClasses, __str__ method
def __str__(self): # Used by print and str(*)s = ‘px %d\n’ % self.px # Uses the C printfs = s + ‘py %d\n’ % self.py # format stringss = s + ‘pz %d\n’ % self.pzs = s = ‘E %d’ % self.ereturn s # Return string
# Note: We could also have written the above # as s = ‘%s %d\n’ % (‘px’,self.px), etc..>>> print ppx 12py -14pz 13E 80
An Introduction to python, Harrison
B. Prosper, 1997
18
Classes, __add__, __sub__ methodsClasses, __add__, __sub__ methodsClasses, __add__, __sub__ methodsClasses, __add__, __sub__ methods
def __add__(self, v): # Implement +u = FourVector()u.px = self.px + v.pxu.py = self.py + v.pyu.pz = self.pz + v.pzu.e = self.e + v.ereturn u
def __sub__(self, v): # Implement -: :
An Introduction to python, Harrison
B. Prosper, 1997
19
Classes, __mul__ methodClasses, __mul__ methodClasses, __mul__ methodClasses, __mul__ method
def __mul__(self, v): # Implement *u = self.px*v.px+self.py*v.py+self.pz*v.pzreturn self.e*v.e - u
>>> p = FourVector(1,2,3,10)>>> q = FourVector(0,0,-1,20)>>> pq = p*q
An Introduction to python, Harrison
B. Prosper, 1997
20
Classes, InheritanceClasses, InheritanceClasses, InheritanceClasses, Inheritance
class Particle(FourVector):def __init__(self, label=‘e-’,px=0,py=0,pz=0,E=0):
# Call FourVector constructor to initialize px, etc.FourVector.__init__(self, px,py,pz,E)
if self.ok: # Check for successself.label = label # Create another attribute
else: return# NB: Constructor return value ignored
def __del__(self):if self.ok: print ‘Goodbye cruel world!’else: print ‘I never got properly made anyway!’
An Introduction to python, Harrison
B. Prosper, 1997
21
Classes, dynamically created attributesClasses, dynamically created attributesClasses, dynamically created attributesClasses, dynamically created attributes
from math import * # Import all math functions
class Particle(FourVector):: :def __getattr__(self, attribute): # Method to get values
# of dynamic attributesif attribute == ‘mass’:
x = sqrt(self.e**2-(self.px**2+self.py**2+self.pz**2))
return xelse: # Okay; have a tantrum!
raise AttributeError, attribute
An Introduction to python, Harrison
B. Prosper, 1997
22
Setting dynamically created attributesSetting dynamically created attributesSetting dynamically created attributesSetting dynamically created attributes
class Particle(FourVector):: :def __setattr__(self, attribute, value): # Method to set
# values of dynamic attributesif attribute == ‘version’:
#NB: Do not write self.version = value here because this# would create a statically defined attribute! Set using the # object’s dictionary attribute:
self.__dict__[attribute] = valueelse:
raise AttributeError, attribute
An Introduction to python, Harrison
B. Prosper, 1997
23
A simple Internet serverA simple Internet serverA simple Internet serverA simple Internet server
from socket import *from os import *def server(PORT=50000): # Choose any non-privileged port
HOST = ‘’ # Local hosts = socket(AF_INET, SOCK_STREAM) # Create sockets.bind(HOST, PORT) # Bind socket to local hosts.listen(1) # Allow only a single queued connectionclient, address = s.accept() # Wait for a connectionwhile 1: # Wait “forever”
data = client.recv(4096) # Get up to 4k bytesif data == ‘quit’: break else: print data
print “Goodbye from server!”
An Introduction to python, Harrison
B. Prosper, 1997
24
A simple internet clientA simple internet clientA simple internet clientA simple internet client
from socket import *from os import *def client(HOST=gethostname(), # Default is local server
PORT=50000): # Server ports = socket(AF_INET, SOCK_STREAM) # Create sockets.connect(HOST, PORT) # Connect to serverwhile 1:
data = raw_input(‘Client> ’)# Get keyboard inputif data == ‘quit’: break else: s.send(data) # Send to server
s.send(‘quit’)s.shutdown(2) # Terminate all pending I/O s.close() # Close connectionprint “Goodbye from client!”
An Introduction to python, Harrison
B. Prosper, 1997
25
And finally, a client/server sessionAnd finally, a client/server sessionAnd finally, a client/server sessionAnd finally, a client/server session
Server:>>> from server import server>>> server()Go Boil your head!Goodbye from server!>>>
Client:>>> from client import client>>> client(‘d02ka.fnal.gov’)Client>> Go boil your head!Client>> quitGoodbye from client!>>>
An Introduction to python, Harrison
B. Prosper, 1997
26
Odds and endsOdds and endsOdds and endsOdds and ends
Changing the python search path on-the-flyimport syssys.path.append(‘~harry/python/tutorial’)sys.path.append(‘~harry/python/examples’)
Spawning commands to the operating systemimport osos.system(‘cd; ls -la’)
Debugging python scripts (type h for help)from pdb import runrun(‘p = FourVector(1,1,2,90)’)
An Introduction to python, Harrison
B. Prosper, 1997
27
Odds and ends (eval, exec, try, except)Odds and ends (eval, exec, try, except)Odds and ends (eval, exec, try, except)Odds and ends (eval, exec, try, except)
Evaluating strings and updating current namespacep = eval(‘FourVector(1,1,2,90)’)
Executing statements and updating current namespace)exec(‘p = FourVector(1,1,2,90)’)
Handling errors>>> s = open(‘FourVector.txt’,’r’).read()>>> try: # Try following statements and. . . p = eval(s) # if an error (i.e., an exception) occurs. . . except: # execute these statements. . . . exec(s) # Note: Can also catch specified>>> print p # exceptions with the except keyword.
An Introduction to python, Harrison
B. Prosper, 1997
28
Graphical User InterfacesGraphical User InterfacesGraphical User InterfacesGraphical User Interfaces
Tk is a widely supported toolkit for building portable Graphical User Interfaces (GUIs). Its purpose is to hide the unbelievable horrors of X windows.
Tkinter is a python module that provides an object-oriented wrapping of Tk. It is available with the standard distribution of python on many different platforms, including Windows NT/95. http://www.pythonware.com/downloads.htm download self-extracting archive (py15-980706.exe) double-click on file to install python
To load all of the Tkinter attributes and methods into the global namespace do: from Tkinter import *
An Introduction to python, Harrison
B. Prosper, 1997
29
Event-driven programsEvent-driven programsEvent-driven programsEvent-driven programs
A GUI application is an example of an event-driven program. An application goes through two steps: Construct GUI layout and bind screen objects
(widgets) to functions (callbacks). Enter a wait loop and bind events to callbacks
Construct GUI layout
WaitForEventDecide which callbacks to callDispatch callbacks
Construct GUI layout
WaitForEventDecide which callbacks to callDispatch callbacks
An Introduction to python, Harrison
B. Prosper, 1997
30
Anatomy of a simple GUIAnatomy of a simple GUIAnatomy of a simple GUIAnatomy of a simple GUI
Frames are containers for Tk objects (widgets).Gui layouts are created by using nested Frames intowhich useful widgets are placed. The root widget provides(platform-dependent) window management.
Entry
Scale
Root
An Introduction to python, Harrison
B. Prosper, 1997
31
GUI Example 1GUI Example 1GUI Example 1GUI Example 1
from Tkinter import * # Add all names to global namespaceimport os
class Gui(Frame): # Gui is an extended Framedef __init__(self, parent=None): # Default parent is root
Frame.__init__(self, parent) # Initialize Frameself.b = Button(self, text=‘List Directory’,
command=self.list, fg=‘red’, bg=‘green’)
self.pack(side=TOP); self.b.pack(side=LEFT)def list(self):
os.system(‘cd; ls -la’)if __name__ == ‘__main__’: Gui.mainloop() # Run as script
An Introduction to python, Harrison
B. Prosper, 1997
32
GUI Example 2GUI Example 2GUI Example 2GUI Example 2
from Tkinter import * #Add all names to global namespacefrom ScrolledText import ScrolledText
class Gui(Frame):def __init__(self, parent=None):
Frame.__init__(self, parent)self.pack()self.config(relief=GROOVE, bd=2)self.master.title(‘Example 2’)self.text = ScrolledText(self)self.text.pack()
if __name__ == ‘__main__’: Gui.mainloop()
An Introduction to python, Harrison
B. Prosper, 1997
33
A couple of other widgetsA couple of other widgetsA couple of other widgetsA couple of other widgets
o is object, p is parent widget, v is value
o = Scale(p, orient=HORIZONTAL, from_= 0, to =1000)v = o.get(), o.set(v)
o = Entry(p), x = StringVar(); o[‘textvariable’] = xo.bind(‘<Key-Return>‘, callback); x.get(), x.set()
An Introduction to python, Harrison
B. Prosper, 1997
34
Python Imaging LibraryPython Imaging LibraryPython Imaging LibraryPython Imaging Library
We shall use this extension (by Frederick Lundh) to build a simple graphics browser (gbrowser.py)
Import modules class Gui(Frame):
Constructor• Get a list of filenames• Loop over filenames
– Create and store full graphics image in a dictionary– Create a button, attach a thumbnail image to it and
bind button to the display method
Display• Paste full image to a label in a separate window
An Introduction to python, Harrison
B. Prosper, 1997
35
A Simple Graphics BrowserA Simple Graphics BrowserA Simple Graphics BrowserA Simple Graphics Browser
from Tkinter import *import Image # Load a couple of PIL import ImageTk # classesimport os, sysfrom string import find, rfind, lowerFILETYPES = (‘.gif’,’.jpg’,’.bmp’) BIG = (768,576); SMALL=(80,60)# Handle different path delimiters between # windows and UNIXif sys.platform == 'win32':
DELIM = "\\" # ‘\’ is the python escape characterelse:
DELIM = "/" # To make UNIX happy :-(
An Introduction to python, Harrison
B. Prosper, 1997
36
Graphics Browser, part 1Graphics Browser, part 1Graphics Browser, part 1Graphics Browser, part 1
class Gui(Frame): # Gui is an extended framedef __init__(self, parent=None, path=('.',)):
# Try to get a listing of given path ( (‘.’,) -- syntax for 1-tuple)try:
files = [] # Create an empty listfor d in path: # path is a tuple of directories
l = os.listdir(d)f = map(lambda x,y=d:y+delim+x,l)files = files + f # Concatenate lists
except:# Come here if listing fails
print "**Errror**, bad directory: ", dsys.exit(1)
An Introduction to python, Harrison
B. Prosper, 1997
37
Graphics Browser, part 2Graphics Browser, part 2Graphics Browser, part 2Graphics Browser, part 2
# Get list of graphics files. # Extract the last 4 characters of each string x in the list files.# Make lower case, then test if the 4-character string matches a# string in the FILETYPES tuple.
gifs = filter(lambda x: lower(x[len(x)-4]) in FILETYPES, files)
# Initialize inherited frameFrame.__init__(self, parent, relief=SUNKEN, bd=2)self.pack()
self.image = {} # Dictionary for imagesrow = col = 0 # For use with grid method
# Next we shall loop over the GIF files and try to read each one
An Introduction to python, Harrison
B. Prosper, 1997
38
Graphics Browser, part 3Graphics Browser, part 3Graphics Browser, part 3Graphics Browser, part 3
for giffile in gifs: # Loop over graphics files# Extract file name
gif = giffile[rfind(giffile,DELIM)+1:] # Search from right
# Exclude duplicate imagesif not self.image.has_key(gif):
print "Reading ", gif, # Note comma to suppress NL
# Read GIF file and create imagetry:
ig = Image.open(giffile)ig.thumbnail(BIG)self.image[gif] = ImageTk.PhotoImage(ig)
An Introduction to python, Harrison
B. Prosper, 1997
39
Graphics Browser, part 4Graphics Browser, part 4Graphics Browser, part 4Graphics Browser, part 4
# Paste button b with a thumbnail version of image.# Note the use of lambda to pass context information to # the single callback self.display
: :ig.thumbnail(SMALL) # 80 x 60 pixelsb = Button(self, image=ImageTk.PhotoImage(ig),
command=lambda s=self, x=gif: s.display(x)): :
An Introduction to python, Harrison
B. Prosper, 1997
40
Graphics Browser, part 5Graphics Browser, part 5Graphics Browser, part 5Graphics Browser, part 5
# Pack using grid method, which requires that we give the row# and column numbers of a matrix. Make buttons expand in all # directions (N+S+E+W) to fill available space.
b.grid(row=row, column=col, sticky=N+S+E+W)col = col + 1 # Update column numberif col == 5:
row = row + 1 # Update row numbercol = 0
print "" # Complete print statementexcept: # associated with Try (see part 3)
print "*** FAILED *** " # Here if we fail to read file
An Introduction to python, Harrison
B. Prosper, 1997
41
Graphics Browser, part6Graphics Browser, part6Graphics Browser, part6Graphics Browser, part6
# Method to display full image
def display(self, gif):top = Toplevel() # Create a separate windowtop.title(gif)top.iconname(gif)Label(top,image=self.image[gif]).pack()
# Note: Because we do not plan to do anything with the# label other than display it, we don’t bother to create a# reference (a name) for the label.
An Introduction to python, Harrison
B. Prosper, 1997
42
Graphics Browser, running itGraphics Browser, running itGraphics Browser, running itGraphics Browser, running it
# Code added at the end to execute file if it is run as a script,# that is: python gbrowser.py [dir1] [dir2] ...
if __name__ == '__main__':
if not sys.argv[1:]: # Check for NO arguments and, ifpath = '.' # none, default to working directory
else: path = sys.argv[1:] # Get arguments
root = Tk() # Create Tk root widget root.title('Graphics Browser')
Gui(root, path).mainloop() # Enter event loop
An Introduction to python, Harrison
B. Prosper, 1997
43
The EndThe EndThe EndThe End
Python in action!Python in action!