Professional Documents
Culture Documents
CONFIDENTIAL
Topics
What is Python? Variables (Types) Code layout & Program flow
If else else if While For loops
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
To run a script
python
myscript.py
Or on Linux include
#!/usr/bin/env python chmod +x myscript.py ./myscript.py
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
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 >>>
Cating strings:
>>> word = ip. + access >>> word ip.access'
Accessing bytes:
>>> word[2] .' >>> word[2:4] .acc >>> len(word) 9
CONFIDENTIAL
Types (Lists)
Lists contain other compound types:
>>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234]
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}
CONFIDENTIAL
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
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
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'
CONFIDENTIAL
Standard library
import os
os.system(ls /tmp) os.chdir(/tmp/)
import logging
Allows standard log functions
import sys
print sys.platform
win32
print sys.argv
[myscript.py,arg1,arg2]
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
In user code:
from mydir.mymod import myclass1 from mydir.myothermod import anotherclass from mydir.anothermod import *
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,
19