You are on page 1of 19

Python 101 an introduction

A pre-cursor to writing TAF scripts 3GAP_TST-TAF_TN_0004 CONFIDENTIAL

CONFIDENTIAL

Topics
What is Python? Variables (Types) Code layout & Program flow
If else else if While For loops

Functions Classes Exceptions Built in libraries


sys time os

Modules and Packages PyDoc PExpect


2

CONFIDENTIAL

What is Python?
Read http://docs.python.org/tutorial/ Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive. Its use of indentation for block delimiters is unusual among popular programming languages. Python was conceived in the late 1980s and its implementation was started in December 1989 by Guido van Rossum Python 2.0 was released on 16 October 2000, with many major new features including a full garbage collector and support for Unicode. However, the most important change was to the development process itself, with a shift to a more transparent and community-backed process. Python 3.0, a major, backwards-incompatible release, was released on 3 December 2008 after a long period of testing. Many of its major features have been back ported to the backwards-compatible Python 2.6 the Python philosophy rejects exuberant syntax, such as in Perl, in favor of a sparser, less-cluttered grammar "To describe something as clever is NOT considered a compliment in the Python culture." Python's philosophy rejects the Perl "there is more than one way to do it" approach to language design in favor of "there should be oneand preferably only oneobvious way to do it".
3

CONFIDENTIAL

Invoking the interpreter


Just type python (or run python.exe from Windows)
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> print "Hello World" Hello World [Ctrl-D to exit]

To run a script
python
myscript.py

Or on Linux include
#!/usr/bin/env python chmod +x myscript.py ./myscript.py

in the 1st line of the script

NOTE: REDHAT 4 uses an old 2.3.4 version. TAF uses Python 2.4 and is installed in /exports/ipaccess/bin. Keep scripts pointing at /usr/bin/env python since we plan to roll out a later REDHAT release at some point.
4

CONFIDENTIAL

Types (Integers / Floats)


Simple integer / float assignments:
>>> width = 20 >>> height = 5*9 >>> width * height 900 >>> x = y = z = 0 # Zero x, y and z >>> x 0 >>> 3 * 3.75 / 1.5 # Floating point (integers converted to floats first) 7.5

CONFIDENTIAL

Types (Strings)
String examples:
>>> 'spam eggs 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.'

Multi-line definitions:
>>>print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to""" Usage: thingy [OPTIONS] -h -H hostname >>>

Display this usage message Hostname to connect to

Cating strings:
>>> word = ip. + access >>> word ip.access'

Accessing bytes:
>>> word[2] .' >>> word[2:4] .acc >>> len(word) 9

See also String library for other methods (e.g. RegEx)


6

CONFIDENTIAL

Types (Lists)
Lists contain other compound types:
>>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234]

Can modify list entries (unlike strings):


>>> a[2] = 'One hundred' >>> a ['spam', 'eggs', 'One hundred', 1234] >>> a[1:3] = [] # Remove some entries >>> a ['spam', 1234]

Lists can contain lists:


>>> b = ['I', 'Love', 'ip.access so much'] >>> a.append(b) >>> a ['spam', 1234, ['I', 'Love', 'ip.access so much']]

CONFIDENTIAL

Types (Dictionaries)
Same as Hash or Associative Arrays in other languages
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098}

You can delete entries using the del operator:


>>> del tel['sape'] >>> tel {'guido': 4127, 'jack': 4098}

Getting the keys with keys():


>>> tel.keys() {'guido', 'jack'}

Iterating through a dictionary:


>>> for k, v in knights.iteritems(): print k, v guido 4127 jack 4098
8

CONFIDENTIAL

Code Layout / Program Flow


if elif else:
a = 2 b = 1 if a > b: # Note the : ! print a is greater than b # Note the indentation elif a == b: # Note elif not else if print a equals b else: print a is less than b print next statement in else clause print next statement after if block This will produce: a is greater than b next statement after if block

For loops:
a=[ip.access,is,fab] for x in a: print x,len(x) This will produce: ip.access 9 is 2 fab 3 for x in range(1,20): print x This will produce: 1 2 20 #built in function

CONFIDENTIAL

Loops (as well as continue and break)


Break / continue statement applies to for and while loops
a=[ip.access,is,fab,again] for x in a: if len(x) == 2: continue: # well skip over is print x,len(x) if len(x) == 3: break: # we wont get as far as again This will produce: ip.access 9 fab 3

While loops:
i = 0 my_condition = True while my_condition == True: i = i + 1 if i > 10: my_condition = False

10

CONFIDENTIAL

Adding functions
Comments:
# this is the first comment SPAM = 1 # and this is the second comment # ... and now a third! STRING = "# This is not a comment."

Functions:

def

myFunction( a, b=1): # Note the :! # Note the indentation again... print a + b = %d%(a+b) # Did you spot the % operator ? print %d - %d = %d%(a,b,a-b) # Note that you need brackets around the arg for formatting # multiple args i.e. is passed as a tuple

if __name__ == __main__: myFunction(1) # b is assumed = 1 since it was optional myFunction(1,3) Will produce: a + b = 2 1 1 = 0 a + b = 4 1 3 = -2
11

CONFIDENTIAL

Classes
Like everything else must be carefully indented
class myBaseClass: Constructor __init__ def __init__(self): pass # pass used as a NOP def setA(self, a=1): self.a = a def dumpMe(self): print A is %d%self.a self arg is 1st in all class functions class myDerivedClass( myBaseClass ): def addA( self, b ): Base class self.a = self.a + b if __name__ == __main__: obj = myDerivedClass() obj.setA(39) obj.dumpMe() obj.addA(3) obj.dumpMe() Will produce: A is 39 A is 42

Constructor returns an object

self arg is not passed when calling functions

12

CONFIDENTIAL

Exceptions
Very elegant solution to handling run-time problems
def doCallA(): doCallB() def doCallB(): f = open(non-existant_file) if __name__ == __main__: doCallA() Will produce: File "<stdin>", line 2, in <module> File "<stdin>", line 2, in doCallA File "<stdin>", line 2, in doCallB IOError: [Errno 2] No such file or directory: 'non-existant_file'

Can catch specific exceptions with try, catch:


if __name__ == __main__: try: doCallA() catch IOError: print File not found! print carry on...!
13

CONFIDENTIAL

Standard library
import os
os.system(ls /tmp) os.chdir(/tmp/)

import logging
Allows standard log functions

import sys
print sys.platform
win32

import socket import socketserver


Can create a simple web server in 10 lines!

print sys.argv
[myscript.py,arg1,arg2]

sys.stderr.write(Something went wrong!\n)

import time
print time.time()
1265067421.4679999

time.sleep(1)

# 1 second delay

import re
Regular expressions

import math
math.cos(math.pi / 4.0)

import random
random.choice([apple,bananna,pear])
bananna

14

CONFIDENTIAL

Modules and Packages


Creating your own modules is simple
Add path to your module to PYTHONPATH or standard python installation area Create directory (e.g. mydir) Create file called __init__.py (can be empty)
This will be sourced when the module is imported

Create module file containing your classes


e.g.
/mydir/ __init__.py mymod.py myothermod.py anothermod.py

In user code:
from mydir.mymod import myclass1 from mydir.myothermod import anotherclass from mydir.anothermod import *

help and dir


From python interpreter you can discover the functions using dir (module) e.g. dir(os)
15

CONFIDENTIAL

Using PyDoc
PYDOC is a mechanism to auto document your code IPA coding standard for Python is to follow this
################################################### # (c) ip.access 2010 ################################################### # File Description: # """ This module does...""" # class myClass(): This class does blah def __init__(self): Constructor for myClass self.a = 0 def doSomething(self): Another bit of documentation if a > b:

To view PyDoc
Run pydoc p 1234 Goto web browser http://localhost:1234
16

CONFIDENTIAL

17

CONFIDENTIAL

PExpect
Not included in standard Python distribution Built upon Expect

TAF uses this heavily, but this is hidden by TAF API helper modules
Example:
#!/usr/bin/env python import pexpect ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line p=pexpect.spawn('ssh mysurface@192.168.1.105') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) if i==0: print "I say yes" p.sendline('yes') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) if i==1: print "I give password, p.sendline("mypassword") p.expect(pexpect.EOF) elif i==2: print "I either got key or connection timeout" pass print p.before # print out the result

18

CONFIDENTIAL

Summary
Python is a high level language, with a powerful standard library More elegant than others like Perl,

Includes built-in Object Oriented constructs


Widely ported to many OSs (there is even a port to Symbian used in Nokia Phones) Current popular version is 2.6 although 3.0 exists it is not backwards compatible with 2.x The info presented here is only scratching the surface
Check the online help at http://docs.python.org/

19

You might also like