Scripting with Python

36
Scripting with Python What is a scripting language? What is Python?

description

What is a scripting language? What is Python?. Scripting with Python. Scripting Languages. Originally, a script was a file containing a sequence of commands that needed to be executed Control structures were added to make it possible to do more with scripts. - PowerPoint PPT Presentation

Transcript of Scripting with Python

Page 1: Scripting with Python

Scripting with Python

What is a scripting language?

What is Python?

Page 2: Scripting with Python

Scripting Languages

• Originally, a script was a file containing a sequence of commands that needed to be executed

• Control structures were added to make it possible to do more with scripts

Page 3: Scripting with Python

Characteristics of Scripting Languages

• Generally interpreted

• Dynamic typing - no declarations

• Make text processing easy

• Often provide pattern matching for strings

• Provide file and directory manipulation

• Make it easy to do things quickly

Page 4: Scripting with Python

Basic Scripting Languages

• Unix and Linux come with shell programs which are programmable – sh– bash– ksh– csh

• DOS had BAT files

Page 5: Scripting with Python

Scripting in Other Environments

• Even with a GUI operating system, it is still useful to be able to automate repetitive tasks– Windows still has bat files– Mac OS has AppleScript

• Some applications have a scripting language built into them– Microsoft applications have Visual Basic for

Applications (VBA)– Hypercard (Apple) had HyperTalk

Page 6: Scripting with Python

Other Scripting Languages

• Other scripting languages were developed to provide increased capability– sed -- adapted from the UNIX ed editor in 1977 – AWK -- created by Ajo, Wienberger and Kernighan

in 1977– Tcl -- an extensible scripting language written by

John Ousterhout in 1987– Perl -- created by Larry Wall in 1986– Python-- created in 1989 by Guido van Rossum– Ruby -- created in 1993 by Yukihiro Matsumoto

Page 7: Scripting with Python

Scripting and the Web

• More recently, a number of scripting languages have been developed for use with web browsers– PHP– JavaScript– ASP (part of Microsoft .NET framework)

Page 8: Scripting with Python

Scripting on onyx

• the shell languages• sed• awk• perl• python• ruby• tcl

• javascript• php

Page 9: Scripting with Python

Python

• An object-oriented scripting language

• Portable (written in ANSI C)

• Powerful - see next slide

• Mixable - can be used in conjunction with other languages

• Easy to use

• Easy to learn

Page 10: Scripting with Python

The Power of Python

• dynamic typing• built-in objects• built-in tools• built-in libraries• garbage collection• modular

Page 11: Scripting with Python

Running Python code

• Run the python interpreter and type the commands in interactively

• Call the interpreter with the name of the scriptpython progName

• Type the program name of an executable script file chmod +x script./script- The first line of the script should be

#!/usr/bin/python

Page 12: Scripting with Python

Hello World

#!/usr/bin/python

import sys

sys.stdout.write("Hello world!\n")

Page 13: Scripting with Python

Python Program Structure• A python program is composed of modules• A python module is composed of statements

– statements are terminated by a newline unless the last character is a \ or there is an unclosed (. [ or {

– Put two statements on a line with a ; between

• Statements create and process objects

Page 14: Scripting with Python

Python Built-in Types

• Numbers (immutable)• Sequences - indexing, slicing, concatenation

– Strings (immutable)– Lists (mutable)– Tuples (immutable)

• Mapping - indexing by key– Dictionaries (mutable)

• Files

Page 15: Scripting with Python

Numbers

• Numeric types– integers - a C long– long integer - arbitrary number of digits– floating point - C double– complex

• Standard arithmetic, comparison, bitwise operators plus ** (exponentiation)

• Built-in functions : pow, abs, …• Modules : rand, math, cmath

Page 16: Scripting with Python

Sequences

• Strings : 'abc', "def", """triple-qouted for multi-line strings"""

• Lists : [1, 2, 4]

• Tuples : (1, 2, 3)

Page 17: Scripting with Python

Sequence Operations

• concatenation with +

• indexing with [ ]

• slicing (substring) with [ : ]

• len( s) to get length

• % for formatting : fmtString % string

• * for repeating

• in for membership : 'a' in str

Page 18: Scripting with Python

Strings

• Immutable, ordered sequences of characters• Supports all sequence operations (see

strings.py)• string module provides other functions• re module supports pattern matching

Page 19: Scripting with Python

string module

• Names must be qualified with the module name (string. )

• upper(str), lower(str) - returns a string

• find( str, substr) returns index of substr

• split( str, delimStr=" ") returns list of string

• join( strList, separator) returns a string

Page 20: Scripting with Python

String class

• As objects, strings have may of the same methods that the string module contains

• Qualify the methods with the name of the string

Page 21: Scripting with Python

Lists

• Ordered collection of arbitrary objects– arrays of object references– mutable– variable length– nestable

• Representation : [0, 1, 2, 3]• list methods modify the list (append, sort)• see lists.py

Page 22: Scripting with Python

Tuples

• Ordered sequence of arbitrary objects

• Immutable

• Fixed length

• Arrays of object references

• Representation : (1, 2, 3)

• Like lists except no mutations allowed

Page 23: Scripting with Python

Dictionary

• Unordered collection of arbitrary objects

• Element access by key, not index (hash table)

• Variable length, mutable

• nestable

• Representation : {'spam' : 2, 'eggs' : 3}

• see dict.py

Page 24: Scripting with Python

Dictionary operations

• element access : d[key]• insert, update : d[key] = 'new'• remove : del d [key]• length: len(d)• methods

– has_key( str)– keys() returns list of keys– values() returns list of values

Page 25: Scripting with Python

Boolean Expressions

• Expression truth values 0, "", [], {}, 0.0, None are all false– everything else is true

• Comparison operators: < <= == != >= >– return True and False (1 and 0)– Python allows a < b < c

• Boolean operators: and or not– return an object which is true or false

Page 26: Scripting with Python

Comparison

• == checks for value equivalence

• is checks for object equivalence

• < <= > >= do element by element comparison– think of how strings are compared in Java

Page 27: Scripting with Python

Python Statements

• Assignment• Function calls• print• if/elif/else• for/else• while/else• Def, return• import, from

• break, continue• pass - no-op• try-except-finally• raise (exception)• class• global• del - delete objects• exec

Page 28: Scripting with Python

Assignment

• Variable names follow the same rules as in C

• Names are created when they are first assigned

• Names must be assigned before they can be referenced

• Assignment creates an object reference• Associativity is right to left

Page 29: Scripting with Python

Assignment examples

spam = 'spam'

spam, ham = 'yum', 'YUM'

[spam, ham] = ['yum', 'YUM']

list = [1, 2, 3]

tuple = ('a', 'b', 'c')

d = {1 : 'one', 2 : 'two', 3 : three}

Page 30: Scripting with Python

Blocks

• Blocks in python are started by a compound statementheader :stmt1…laststmt

• Blocks terminate when the indentation level is reduced

Page 31: Scripting with Python

if

• Syntaxif test1:

block1

elif test2:

block2

else:

elseblock

• else and elif are optional

• Can have arbitrary number of elif

Page 32: Scripting with Python

while• Syntaxwhile test:

loopbodyelse:

nobreakaction• Optional else part is executed if loop exits

without a break • break and continue work as in Java• pass is a null statement used for empty body

Page 33: Scripting with Python

for

• for loop is a sequence iterator

• works on strings, lists, tuples

• range is a function that generates a list of numbers

for var in seq

loopbody

else:

nobreakaction

Page 34: Scripting with Python

Functions

• Define with

def fun(p1, p2):

return p1 + p2• Call with

fun(2, 3)• Function without a

return statement returns None

• Names are local unless declared global

• Variables are references – assigning to a

parameter does not change the caller

– changing a mutable object does change the caller

Page 35: Scripting with Python

Scope

• Python has three scopes– local (in function)– global (in module)– built-in

• Nested functions do not have nested scope

Page 36: Scripting with Python

os Module• Provides a portable way to do OS-

dependent operations– manipulating files and directories

• listdir( path)• mkdir( path)• chmod( path, mode)

– process management• fork, exec, kill• system( command)

– system information