scripting with python
Post on 01-Jan-2016
68 Views
Preview:
DESCRIPTION
TRANSCRIPT
Scripting with Python
What is a scripting language?
What is 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
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
Basic Scripting Languages
• Unix and Linux come with shell programs which are programmable – sh– bash– ksh– csh
• DOS had BAT files
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
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
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)
Scripting on onyx
• the shell languages• sed• awk• perl• python• ruby• tcl
• javascript• php
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
The Power of Python
• dynamic typing• built-in objects• built-in tools• built-in libraries• garbage collection• modular
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
Hello World
#!/usr/bin/python
import sys
sys.stdout.write("Hello world!\n")
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
Python Built-in Types
• Numbers (immutable)• Sequences - indexing, slicing, concatenation
– Strings (immutable)– Lists (mutable)– Tuples (immutable)
• Mapping - indexing by key– Dictionaries (mutable)
• Files
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
Sequences
• Strings : 'abc', "def", """triple-qouted for multi-line strings"""
• Lists : [1, 2, 4]
• Tuples : (1, 2, 3)
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
Strings
• Immutable, ordered sequences of characters• Supports all sequence operations (see
strings.py)• string module provides other functions• re module supports pattern matching
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
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
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
Tuples
• Ordered sequence of arbitrary objects
• Immutable
• Fixed length
• Arrays of object references
• Representation : (1, 2, 3)
• Like lists except no mutations allowed
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
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
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
Comparison
• == checks for value equivalence
• is checks for object equivalence
• < <= > >= do element by element comparison– think of how strings are compared in Java
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
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
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}
Blocks
• Blocks in python are started by a compound statementheader :stmt1…laststmt
• Blocks terminate when the indentation level is reduced
if
• Syntaxif test1:
block1
elif test2:
block2
else:
elseblock
• else and elif are optional
• Can have arbitrary number of elif
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
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
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
Scope
• Python has three scopes– local (in function)– global (in module)– built-in
• Nested functions do not have nested scope
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
top related