Download
an introduction to python n.
Skip this Video
Loading SlideShow in 5 Seconds..
An Introduction to Python PowerPoint Presentation
Download Presentation
An Introduction to Python

An Introduction to Python

228 Views Download Presentation
Download Presentation

An Introduction to Python

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. An Introduction toPython Harrison B. Prosper Florida State University An Introduction to python, Harrison B. Prosper, 1997

  2. Acknowledgements • 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. Outline • 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? • Python is a scripting language, created by Guido van Rossum (guido@CNRI.Reston.VA.US), 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 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) fromstring 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. printsize, l[j] else:LOOK MA, NO BRACES BECAUSE print l[j] PYTHON USES INDENTATION! An Introduction to python, Harrison B. Prosper, 1997

  7. Namespaces __builtins__ len, xrange, dir, open,... Global (import) __builtins__ os f, s, atoi, split l, n, j, a, size popen, system, listdir, environ, path,... An Introduction to python, Harrison B. Prosper, 1997

  8. Looking at namespaces l = dir() Create a list of the names for j in xrange(len(l)): in theglobal namespace print l[j] l = dir(__builtins__) Create a list of the names in the namespace of the module __builtins__ l = dir(os) Dolikewise for the moduleos An Introduction to python, Harrison B. Prosper, 1997

  9. 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) from string import strip, find #Import strip and find t = 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 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) 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) >>> 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) >>> 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) def goofy(a, b=‘yahoo’,*t, **k): # a is arequired 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, b 1 2001 An Introduction to python, Harrison B. Prosper, 1997

  16. Classes class FourVector: #Name of class def __init__(self, px=0,py=0,pz=0,E=0): #Constructor self.ok = 1 # Creation ok if E >= 0: self.px, self.py, self.pz, self.e = px,py,pz,E else: self.ok = 0 # Creation failed def __del__(self): #Destructor pass >>> p = FourVector(12,-14,13,80) An Introduction to python, Harrison B. Prosper, 1997

  17. Classes, __str__ method def __str__(self): #Used by print and str(*) s = ‘px %d\n’ % self.px # Uses the C printf s = s + ‘py %d\n’ % self.py # format strings s = s + ‘pz %d\n’ % self.pz s = s = ‘E %d’ % self.e return s #Return string #Note: We could also have written the above # as s = ‘%s %d\n’%(‘px’,self.px), etc.. >>> print p px 12 py -14 pz 13 E 80 An Introduction to python, Harrison B. Prosper, 1997

  18. Classes, __add__, __sub__ methods def __add__(self, v): #Implement + u = FourVector() u.px = self.px + v.px u.py = self.py + v.py u.pz = self.pz + v.pz u.e = self.e + v.e return u def __sub__(self, v): #Implement - : : An Introduction to python, Harrison B. Prosper, 1997

  19. Classes, __mul__ method def __mul__(self, v): # Implement * u = self.px*v.px+self.py*v.py+self.pz*v.pz return 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, 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 success self.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 attributes from math import * #Import all math functions class Particle(FourVector): : : def __getattr__(self, attribute): # Method to get values # of dynamic attributes if attribute == ‘mass’: x = sqrt(self.e**2 -(self.px**2+self.py**2+self.pz**2)) return x else: # Okay; have a tantrum! raise AttributeError, attribute An Introduction to python, Harrison B. Prosper, 1997

  22. Setting dynamically created attributes class Particle(FourVector): : : def __setattr__(self, attribute, value): # Method to set # values of dynamic attributes if 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] = value else: raise AttributeError, attribute An Introduction to python, Harrison B. Prosper, 1997

  23. A simple Internet server from socket import * from os import * def server(PORT=50000): # Choose any non-privileged port HOST = ‘’ # Local host s = socket(AF_INET, SOCK_STREAM) # Create socket s.bind(HOST, PORT) # Bind socket to local host s.listen(1) # Allow only a single queued connection client, address = s.accept() # Wait for a connection while 1: # Wait “forever” data = client.recv(4096) # Get up to 4k bytes if data == ‘quit’: break else: print data print “Goodbye from server!” An Introduction to python, Harrison B. Prosper, 1997

  24. A simple internet client from socket import * from os import * def client(HOST=gethostname(), # Default is local server PORT=50000): # Server port s = socket(AF_INET, SOCK_STREAM) # Create socket s.connect(HOST, PORT) # Connect to server while 1: data = raw_input(‘Client> ’)# Get keyboard input if data == ‘quit’: break else: s.send(data) # Send to server s.send(‘quit’) s.shutdown(2) # Terminate all pending I/O s.close() # Close connection print “Goodbye from client!” An Introduction to python, Harrison B. Prosper, 1997

  25. And 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>> quit Goodbye from client! >>> An Introduction to python, Harrison B. Prosper, 1997

  26. Odds and ends Changing the python search path on-the-fly import sys sys.path.append(‘~harry/python/tutorial’) sys.path.append(‘~harry/python/examples’) Spawning commands to the operating system import os os.system(‘cd; ls -la’) Debugging python scripts (type h for help) from pdb import run run(‘p = FourVector(1,1,2,90)’) An Introduction to python, Harrison B. Prosper, 1997

  27. Odds and ends (eval, exec, try, except) Evaluating strings and updating current namespace p = 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 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 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 WaitForEvent Decide which callbacks to call Dispatch callbacks An Introduction to python, Harrison B. Prosper, 1997

  30. Anatomy of a simple GUI Root Entry Scale Frames are containers for Tk objects (widgets). Gui layouts are created by using nested Frames into which useful widgets are placed. The root widget provides (platform-dependent) window management. An Introduction to python, Harrison B. Prosper, 1997

  31. GUI Example 1 from Tkinter import * #Add all names to global namespace import os class Gui(Frame): #Gui is an extended Frame def __init__(self, parent=None): # Default parent is root Frame.__init__(self, parent) # Initialize Frame self.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 2 from Tkinter import * #Add all names to global namespace from 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 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’] = x o.bind(‘<Key-Return>‘, callback); x.get(), x.set() An Introduction to python, Harrison B. Prosper, 1997

  34. Python 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 Browser from Tkinter import * import Image# Load a couple of PIL import ImageTk# classes import os, sys from string import find, rfind, lower FILETYPES = (‘.gif’,’.jpg’,’.bmp’) BIG = (768,576); SMALL=(80,60) # Handle different path delimiters between # windows and UNIX if sys.platform == 'win32': DELIM = "\\" # ‘\’ is the python escape character else: DELIM = "/" # To make UNIX happy :-( An Introduction to python, Harrison B. Prosper, 1997

  36. Graphics Browser, part 1 class Gui(Frame): # Gui is an extended frame def __init__(self, parent=None, path=('.',)): # Try to get a listing of given path ( (‘.’,) -- syntax for 1-tuple) try: files = [] # Create an empty list for 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: ", d sys.exit(1) An Introduction to python, Harrison B. Prosper, 1997

  37. Graphics 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 frame Frame.__init__(self, parent, relief=SUNKEN, bd=2) self.pack() self.image = {} # Dictionary for images row = 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 3 for giffile in gifs: # Loop over graphics files # Extract file name gif = giffile[rfind(giffile,DELIM)+1:] # Search from right # Exclude duplicate images if not self.image.has_key(gif): print "Reading ", gif, # Note comma to suppress NL # Read GIF file and create image try: 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 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 pixels b = 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 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 number if col == 5: row = row + 1 # Update row number col = 0 print "" # Complete print statement except: # 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, part6 # Method to display full image def display(self, gif): top = Toplevel() # Create a separate window top.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 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, if path = '.' # 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 End Python in action! An Introduction to python, Harrison B. Prosper, 1997