Академический Документы
Профессиональный Документы
Культура Документы
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 36
More on Strings
Special string methods (excerpt)
s = " Frodo and Sam and Bilbo " s . islower () s . isupper () s . startswith ( " Frodo " ) # try s . startswith (" Frodo " , 2) s . endswith ( " Bilbo " ) s = s . strip () s . upper () s = s . lower () s . capitalize () # capitalize first character s = s . center ( len ( s )+4) # center ( padding default : space ) s . lstrip () s . rstrip ( " " ) s = s . strip () s . find ( " sam " ) s . rfind ( " and " )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 37
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 39
More on Functions
Functions have to be dened before actually called for the rst
time
Variables
Variables dened or assigned to in functions have local scope Global variables (surrounding context) can be accessed To modify global variables use global count = 0 ... def count_it ( n ): global count count += 1 In general: avoid global variables (pass as params instead)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 40
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 41
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 42
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 43
Docstrings
Functions (and classes, modules, ...) can provide help text String after function header (can be multiline) def answer (): " Returns an answer to a question " print " answer " help ( answer )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 44
Arithmetic Operations
Classical operations
x x x x x x x x + y # Addition - y # Subtraction * y # Multiplication / y # Division // y # Truncated division ** y # Exponentiation % y # Modulo -= 2; x *= 4; ... Division differs for int and float (Python < 3.0) 7/4 7.0/4
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 45
More Operations
General functions
abs ( x ) divmod (x , y ) pow (x , y [ , modulo ]) round (x , [ n ]) # ( x // y , x % y ) # x ** y % modulo # round to 10**( - n )
Operations on integers
x << y x >> y x & y x | y x ^ y ~x # # # # # # Left shift Right shift Bitwise and Bitwise or Bitwise xor Bitwise negation
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 46
File I/O
Opening les
Create le object (text les) fd fd fd fd = = = = open ( " testfile . txt " ) open ( " testfile . txt " , r ) open ( " testfile . txt " , w ) open ( " testfile . txt " , a ) # # # # read read write append
Create le object (binary les) fd = open ( " testfile . txt " , rb ) fd = open ( " testfile . txt " , wb ) fd = open ( " testfile . txt " , ab ) # read # write # append
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 49
Some more functions on le objects fd.tell() get current le position fd.seek(offset) set le to position fd.flush() ush output buffer. Note: buffered for efciency
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 49
Getting more. . .
Modules Outsource functionality in separate .py les Import them as library module Example (tools.py):
""" This module provides some helper tools . Try it . """ counter = 42 def readfile ( fname ): " Read text file . Returns list of lines " fd = open ( fname , r ) data = fd . readlines () fd . close () return data def do_nothing (): " Do really nothing " pass
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 50
Modules (2)
Import module import tools tools . do_nothing () print tools . counter Import module and change name import tools as t t . do_nothing () Import selected symbols to current namespace from tools import do_nothing , readfile from tools import counter as cntr do_nothing () print cntr
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 51
Modules (3)
Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools . py __all__ = [ readfile , counter ]
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 52
Modules (3)
Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools . py __all__ = [ readfile , counter ]
Then do_nothing() is unknown after import * Inspect namespace Inspect namespace of module with
dir ( tools )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 52
Modules (4)
Getting help Access docstrings
import tools help ( tools ) help ( tools . do_nothing )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 53
Modules (4)
Getting help Access docstrings
import tools help ( tools ) help ( tools . do_nothing )
Execute module as main program tools.py should serve as program and module
# tools . py ... if __name__ == __main__ : print " tools . py executed " else : print " tools . py imported as module "
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 53
Modules (5)
Reload module
When debugging a module reload with reload (Python<3.0) reload ( tools )
path
import sys sys . path . append ( " folder / to / module " ) import ...
Packages
Group modules Modules can be grouped together Folder structure determines modules, e.g.:
tools / __init__ . py files . py graphics . py stringtools / __init__ . py ... further
# contents for " import tools " # for " import tools . files " # for " import tools . graphics " # for " import tools . stringtools " nesting
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 55
Command-Line Options
Using sys
sys.argv is list of command-line options First one (sys.argv[0]) is program name import sys print " Executing : % s " % ( sys . argv [0]) if len ( sys . argv ) < 2: print " Not enough parameters " sys . exit (1) print " Parameters : " print " , " . join ( sys . argv [1:]) Parse parameters...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 56
Try (parameters.py): ./ parameters . py ./ parameters . py -h ./ parameters . py -o " Enjoy it " -- verbose ./ parameters . py -v file1 . txt file2 . txt
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 58
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 59
write only
import sys sys . stdout . write ( " Enter line :\ n " ) # = print "..." line = sys . stdin . readline () # or : line = raw_input (" Enter line :\ n ") if error : sys . stderr . write ( " Error !\ n " ) write does not add newlines raw_input([text]) strips endling newline Input and output buffered
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 60
More on Lists
List comprehension
Short notation to create lists even_squares = [] for i in range (10): if i %2 == 0: even_squares . append ( i * i ) even_squares = [ i **2 for i in range (10) if i %2==0]
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 61
More on Lists
List comprehension
Short notation to create lists even_squares = [] for i in range (10): if i %2 == 0: even_squares . append ( i * i ) even_squares = [ i **2 for i in range (10) if i %2==0]
Can contain more than one for ... in ... [if ...] [( x , y . upper ()) for x in range (4) if x %2 == 0 for y in [ " a " , " b " , " c " ]]
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 61
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 62
range([i,] j [, stride]) creates list Memory allocated for whole list, even when only iterating over xrange object calculates values when accessed (generator) for i in range (650000): do_something () for i in xrange (650000): do_something ()
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 62
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 64