Escolar Documentos
Profissional Documentos
Cultura Documentos
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 1
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 2
Python
Invented in 1990 as teaching language Designed for clearness and readability Named after Monty Python (not the snake)
machines and clusters, web servers, Palm and other Handhelds, Nokia Mobiles, .NET virtual machines, . . .
Versatile Easy to learn, understand, use, and maintain (really!) Free, open-source ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 3 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 4
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 5
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 6
Requirements
Note
Were assuming Python 2.5.X, 2.6.X, or 2.7.X The current version Python 3.X requires few changes
independent of Python
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 6
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 7
$ python Python 2.7.3 ( default , Aug 1 2012 , 05:14:39) [ GCC 4.6.3] on linux2 Type " help " , " copyright " , " credits " or " license " for more information . >>> help Type help () for interactive help , or help ( object ) for help about object . >>> help ()
Welcome to Python 2.7! utility . [...] This is the online help
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 8
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 9
Getting help
>>> print " Hello World ! " Hello World ! Compare with Java, e.g.: public class Hello { public static void main ( String argv []){ System . out . println ( " Hello World ! " ); } }
Literature
David M. Beasley: Python - Essential Reference, Addison-Wesley Professional, 4th edition, 2009 Hans Petter Langtangen: A Primer on Scientic Programming with Python, Springer, 2009
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
1. Start the Python interpreter with python 2. Use IPython: ipython 3. Run Python on a le 3.5. Execute as a script
assignment: variableName = expression (different to math. =) Interactive session shows return values print prints variables and expressions as string
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 12
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 13
2. IPython
$ ipython Python 2.7.3 ( default , Aug 1 2012 , 05:14:39) Type " copyright " , " credits " or " license " for more information .
IPython 0.13.2. rc2 -- An enhanced Interactive Python . ? -> Introduction and overview of IPython s features . % quickref -> Quick reference . help -> Python s own help system . object ? -> Details about object . ? object also works , ?? prints more . In [1]: print " Hello World !" Hello World !
2. IPython
Highlights
Enhanced interactive shell Additional shell syntax
magic functions, starting with % such as %psearch to search for function in namespace Access shell commands %cd Run scripts with run filename.py Log session, dene macros, . . . Pretty printing, toggle with %Pprint
Automatic indentation
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 14 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 15
Just tell shell to execute python: # !/ usr / bin / python print 6**2 Then set executable ag and run
$ python square_me . py 36
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 16
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 17
print True , False True == True True != True int integer 1+5 -12 Attention integer division: digits after the comma get lost! >>> 5/3 1 long arbitrary-precision integer 12345**100
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 18
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 19
General Remarks
Everything is an object (int, oat, tuple, classes, . . . ) Thus everything can have attributes and methods c = complex (2 ,3) print c . real , c . imag Dynamic typing: Type of a variable determined during Automatic conversion where necessary and possible a = 1234 type ( a ) b = 100 type ( b ) a = 1234**100 type ( a ) b = b *1.0 # equals b = float ( b )*1.0 type ( b )
Tobias Neckel: Scripting with Python... and beyond 20 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 21
assignment
Built-in Sequences
Strings
string type Sequence of characters Single, double or triple double (multiline) quotes " ... there lived a hobbit . " " a hobbit " a " hobbit " a \ hobbit \ """ In a hole in the ground there " lived " a hobbit """ Concatenation s1 = " In a hole in the ground " s2 = " there lived a hobbit " s = s1 + + s2 print s
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 22
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 23
Built-in Sequences
Tuples Sequences of arbitrary objects (,) Immutable Indexing and slicing as before
l = (1 ,) l = (1 , " two " , (3 ,4 ,5)) l [0] l [ -1] l [1] = 2 # error len ( l ) min ( l ) # here : numbers smaller than strings l = ( " Hello " , " Hobbit " ) min ( l ) max ( l ) l2 = l + (6 ,7 ,8)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 24
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 25
Built-in Sequences
Lists Sequences of arbitrary objects [,] Mutable
l = [1 , " two " , (3 ,4 ,5) , 5] l [0] l [ -1] l [1] = 2 # works ! len ( l ) Operations on lists l = [0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9] l [2:4] = [10 , 11] l [1:7:2] = [ -1 , -2 , -3] del l [::2]
Built-in Sequences
Lists (2) List methods
l = [0 ,1 ,2 ,3] l . append ( " four " ) l . extend ([5 ,6 ,7 ,8 ,9]) l . insert (8 , " four " ) l . count ( " four " ) l . sort () l . reverse () l . remove ( " four " ) l . pop () Integer ranges: range function range (10) range (5 , 10) range ( -10 , 20 , 3)
Tobias Neckel: Scripting with Python... and beyond 26 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 27
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Control Flow
General
Indentation used to group blocks! Code within same block has to be same level Needs getting used to, but encourages readable code
if-statement
if x < y : print print elif x == print else : print print " x is smaller " x y: " both are equal " " y is smaller " y
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 28
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 29
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 30
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 31
Functions (2)
Default arguments def printme ( s = " Frodo " ): print s printme () printme ( " Bilbo " ) Keyword arguments def exp ( basis , exponent ): return basis ** exponent exp ( basis =2 , exponent =10) exp ( exponent =10 , basis =2)
Up to now. . .
Variables Numeric types Sequence types (str, tuple, list; more tomorrow) if comparison for, while, break, continue Functions and parameters
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 34
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 35
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 36 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 37
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
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 Munchen Scientic Computing in Computer Science, Technische Universitat 40
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 41
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 42
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 43
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
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 Munchen Scientic Computing in Computer Science, Technische Universitat 44
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 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 )
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
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
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 Munchen Scientic Computing in Computer Science, Technische Universitat 49
Getting more. . .
Modules Outsource functionality in separate .py les Import them as library module Example (tools.py):
""" This module pro v ide s 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
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 Munchen Scientic Computing in Computer Science, Technische Universitat 49
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 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 Munchen Scientic Computing in Computer Science, Technische Universitat 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 Munchen Scientic Computing in Computer Science, Technische Universitat 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 ]
Modules (4)
Getting help Access docstrings
import tools help ( tools ) help ( tools . do_nothing )
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 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 )
Modules (5)
Reload module
When debugging a module reload with reload (Python<3.0) reload ( tools )
Module search path 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 " Modules have to be in current directory or in directory in search
path
import sys sys . path . append ( " folder / to / module " ) import ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
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
Command-Line Options
Using sys
sys.argv is list of command-line options First one (sys.argv[0]) is program name # contents for " import tools " # for " import tools . files " # for " import tools . graphics " # for " import tools . stringtools " nesting 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 Munchen Scientic Computing in Computer Science, Technische Universitat 55
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 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 Munchen Scientic Computing in Computer Science, Technische Universitat 58
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]
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 Munchen Scientic Computing in Computer Science, Technische Universitat 60
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 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 Munchen Scientic Computing in Computer Science, Technische Universitat 61
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 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 Munchen Scientic Computing in Computer Science, Technische Universitat
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 64
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 65
What is an object?
What is an object?
a car a cat a chair ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 66
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 66
What is an object?
a car a cat a chair ... a molecule a star a galaxy ...
What is an object?
a car a cat a chair ... a molecule a star a galaxy ... anything that represents a real thing anything that represents an abstract thing anything which has some properties
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 66
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 66
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 67
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 68
Theory: self
Usage of an object
Access to methods: object.method(...) Example: list.append(x) Access to variables: object.variable Example: complex.real
self always is the rst formal parameter, but is skipped at a call Within methods: access to other methods and variables via self.variable and self.method(), resp.
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 71
Theory: Methods
. . . implement the behaviour of objects. . . . represent all types of changes of an object after initialisation. accessor methods: give info on state of an object mutator methods: change state of an object
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
properties
All data is stored in the object itself Whenever lots of data elements are associated with an action,
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 75
Inheritance
Classes can inherit from a base class / superclass This makes them a derived class / subclass of the superclass All classes can be specialized they become superclasses All classes together form a class hierarchy (taxonomy) Properties of the superclass can be taken over or can be redened
# !/ usr / bin / python class MasterStudent ( GRSEmployee ): def __init__ ( self , name , thesis ): self . thesis = thesis GRSEmployee . __init__ ( self , name ) def printInfo ( self ): print " % s works on % s " % ( self . name , self . thesis ) person3 = MasterStudent ( " Terry " , " Terry s thesis topic " ) person3 . printInfo ()
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 76 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
object
77
chair furniture
mammal
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 77
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 77
Golf Polo Phaeton laptop desktop vectorc. cluster croc. snake mule
77
mammal
tree flower
mammal
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Information Hiding
public
Per default: everything (all variables/methods) Comfortable (access from outside) Often dangerous / undesired
private
External access (i.e. from outside the class) forbidden
Syntax: starting with __, but not ending with __ (__privateVar, __privateMet())
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 78
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 79
More on Maths
Module math
Constants pi and e
Functions that operate on int and float All return values float ceil ( x ) floor ( x ) exp ( x ) fabs ( x ) ldexp (x , i ) log ( x [ , base ]) log10 ( x ) modf ( x ) pow (x , y ) sqrt ( x )
# same as globally defined abs () # x * 2** i # == log (x , 10) # ( fractional , integer part ) # x ** y
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 80
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 81
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 82
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 82
Very exible, but slow Loops are not very efcient either
required
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 83
Very exible, but slow Loops are not very efcient either
NumPy
required
Modules
NumPy Matplotlib SciPy
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 83
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 84
Module numpy
Homogeneous arrays
NumPy provides arbitrary-dimensional homogeneous arrays Example from numpy import * a = array ([[1 ,2 ,3] ,[4 ,5 ,6]]) print a type ( a ) a . shape print a [0 ,2] a [0 ,2] = -1 b = a *2 print b
Array creation
Create from (nested) sequence type Direct access with method [] a = array ([1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]) a [1] a = array ([[1 ,2 ,3 ,4] ,[5 ,6 ,7 ,8]]) a [1 ,1] a = array ([[[1 ,2] ,[3 ,4]] ,[[5 ,6] ,[7 ,8]]]) a [1 ,1 ,1]
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 85
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 86
Array creation
Create from (nested) sequence type Direct access with method [] a = array ([1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]) a [1] a = array ([[1 ,2 ,3 ,4] ,[5 ,6 ,7 ,8]]) a [1 ,1] a = array ([[[1 ,2] ,[3 ,4]] ,[[5 ,6] ,[7 ,8]]]) a [1 ,1 ,1] Properties of arrays a . ndim a . shape a . size a . dtype a . itemsize # # # # # number of dimensions dimensions number of elements data type number of bytes
Data Types
Exact, C/C++-motivated type of array elements can be specied Otherwise, defaults are used Some types (different storage requirements): int_, int8, int16, int32, int64, float_, float8, float16, float32, float64, complex_, complex64, bool_, character, object_ Standard python type names result in default behaviour array ([[1 ,2 ,3] ,[4 ,5 ,6]] , dtype = int ) array ([[1 ,2 ,3] ,[4 ,5 ,6]] , dtype = complex ) array ([[1 ,2 ,3] ,[4 ,5 ,6]] , dtype = int8 ) array ([[1 ,2 ,3] ,[4 ,5 ,1000]] , dtype = int8 ) # wrong array ([[1 ,2 ,3] ,[4 ,5 , " hi " ]] , dtype = object ) Exception: object_ stores pointers to objects
Tobias Neckel: Scripting with Python... and beyond 86 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 87
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Create Arrays
(Some) default matrices (optional parameter: dtype) arange ([ a ,] b [ , stride ]) zeros ( (3 ,4) ) ones ( (1 ,3 ,4) ) empty ( (3 ,4) ) linspace (a , b [ , n ]) logspace (a , b [ , n ]) identity ( n ) # as range , 1 D
Manipulate Arrays
Reshaping arrays a = arange (12) b = a . reshape ((3 ,4)) a . resize ((3 ,4)) a . transpose () a . flatten ()
# # # #
# in - place !
fromfunction ( lambda i , j : i +j , (3 ,4) , dtype = int ) def f (i , j ): return i + j fromfunction (f , (3 ,4) , dtype = int )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 88
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 89
a = loadtxt ( " matrix . txt " ) # fromfile () if binary # plenty of options : comments , delim . , usecols , ... Matrix output a . tolist () savetxt ( " matrix . txt " , a )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Array Access
Iterating over entries for row in a : print row b = arange (30); b . resize ((2 ,3 ,4)) for row in b : for col in row : print col for entry in a . flat : print entry
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
Submodules
Module numpy.random
Draw from plenty of different distributions More powerful than module random Work on and return arrays from numpy . random import * binomial (10 , 0.5) # 10 trials , success 50% binomial (10 , 0.5 , 15) randint (0 , 10 , 15) # [0 ,10) , int rand () rand (3 ,4) # [0 ,1) #
(3 x4 ) array
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 94
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 95
Submodules (2)
Module numpy.linalg
Core linear algebra tools norm ( a ); norm ( x ) inv ( a ) solve (a , b ) # LAPACK LU decomp . det ( a ) eig ( a ) cholesky ( a )
Submodules (2)
Module numpy.linalg
Core linear algebra tools norm ( a ); norm ( x ) inv ( a ) solve (a , b ) # LAPACK LU decomp . det ( a ) eig ( a ) cholesky ( a )
Module numpy.fft
Fourier transforms
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 96
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 96
Submodules (2)
Module numpy.linalg
Core linear algebra tools norm ( a ); norm ( x ) inv ( a ) solve (a , b ) # LAPACK LU decomp . det ( a ) eig ( a ) cholesky ( a )
Matplotlib
Module numpy.fft
Fourier transforms
There is more. . .
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 96
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 97
Matplotlib
What is it?
Object-oriented library for plotting 2D Designed to be similar to the matlab plotting functionality Designed to plot scientic data, built on numpy datastructures
Version Mania
Numpy, scipy, ipython and matplotlib often used together They somehow depend on each other (e.g. matplotlib uses
Pylab is a (unofcial) package containing all four Depending on your linux distribution, you might have to install
different packages
This changes the module names from which you have to import
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Example - Histogram
# start ipython - pylab or use imports : # from matplotlib . mlab import * # from matplotlib . pyplot import * from numpy import * mu , sigma = 100 , 15 x = mu + sigma * random . randn (10000) n , bins , patches = hist (x , 50 , normed =1 , \ facecolor = green , alpha =0.75) # add a best fit line y = normpdf ( bins , mu , sigma ) plot ( bins , y , r - - , linewidth =1) axis ([40 , 160 , 0 , 0.03]) plt . show ()
# previous slide continued subplot (2 ,1 ,1) grid ( True ) title ( A tale of 2 subplots ) ylabel ( Damped oscillation ) subplot (2 ,1 ,2) grid ( True ) xlabel ( time ( s ) ) ylabel ( Undamped )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 102
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 103
SciPy
necessary)
Here, just a short overview will be given www.scipy.org for more material (incl. the content of the
following slides)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 104
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 105
Special Functions
Airy functions Elliptic functions Bessel functions (+ Zeros, Integrals, Derivatives, Spherical,
Ricatti-) Struve functions A large number of statistical functions Gamma functions Legendre functions Orthogonal polynomials (Legendre, Chebyshev, Jacobi,...) Hypergeometric functios parabolic cylinder functions Mathieu functions Spheroidal wave functions Kelvin functions ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 107
import numpy as np import matplotlib . pyplot as plt from scipy import interpolate x = np . arange (0 ,10) y = np . exp ( - x /3.0) f = interpolate . interp1d (x , y ) xnew = np . arange (0 ,9 ,0.1) plt . plot (x ,y , o , xnew , f ( xnew ) , - ) plt . title ( Linear interpolation ) plt . show ()
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 108
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 109
Module random
Compute and use pseudo-random numbers
from random import * print random () print choice ([1 ,4 , " Hello " ]) (Re)initialize random with seed([x]) (def: time)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 110
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 111
Module random
Compute and use pseudo-random numbers from random import * print random () print choice ([1 ,4 , " Hello " ]) (Re)initialize random with seed([x]) (def: time) Random oats random () # [0.0 , 1.0) uniform (a , b ) # [a , b ) expovariate ( lambd ) # [0.0 , + inf ) normalvariate ( mu , sigma ) ...
Random integers randint (a , b ) Random sequences choice ( seq ) sample ( seq , len ) shuffle ( l ) # a <= r <= b
# in place ( list )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 111
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 112
Opens new shell: shell=True Runs command echo Hello World Creates le object (read only) for stdout of shell
Opens new shell: shell=True Runs command echo Hello World Creates le object (read only) for stdout of shell Call directly without shell
p = sp . Popen ([ " echo " , " first param " , " second " ] , stdout = sp . PIPE )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 113
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
Some general purpose methods os . getcwd () os . chdir ( path ) os . getgroups () os . uname () os . times () ...
Tobias Neckel: Scripting with Python... and beyond 114 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 115
File objects for stdin and stdout+stderr I/O bufferred (flush() if necessary)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
walk ( path [ , topdown ]) # traverse dir rec . # ( dirpath , dirnames , fnames ) for each dir
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 116
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 117
Regular Expressions
Pattern Syntax Regular expressions should always be placed in a raw string E.g. r([^.]*.(.*)) . match any character but newline ^ match start of the string $ match end of the string * match previous expression zero or more times (greedy) + match previous expression one or more times (greedy) ? match previous expression zero or one time (greedy) *?, +?, ?? non-greedy versions of *, +, ? {m} match previous expression m times {m,n} match previous expression m to n times (greedy) {m,n}? non-greedy version of {m,n} [...] match any character from the enclosed set [^...] match any character not in the set A|B matches A or B (both regular expressions) (...) stores the contents of the match inside the backets
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 119
\number \d \D \s \S \w \W \A \Z
match the text matched by group number (starting from 1) same as [0-9] same as [^0-9] matches any whitespace (same as [\t\n\r\f\v] matches nonwhitespace matches any alphanumeric character matches nonalphanumeric characters matches the start of a string matches the end of a string
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013
Match Objects
Some re functions do not return strings, but match objects (m) match(patt, string) returns MatchObject in case of match search(patt, string) searches for rst match finditer(patt, string) like ndall, but returns iterator m.group([group1, group2]) returns subgroups of the match import re s = " dates 05/02/2010 - 05/14/2010 " patt = r (\ d +)/(\ d +)/(\ d +) for m in finditer ( patt , s ): print m . group () print ( " %s -% s " % ( m . group (2) , m . group (3)))
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 122
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 123
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 123
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 124
your own):
raise RuntimeError ( " Ooops ! Something went wrong ! " ) raise IOError ( " File not existent ... " )
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 125 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 125
Built-in Exceptions
BaseException # GeneratorExit Key boardInterrupt # SystemExit # Exception # StopIteration StandardError # ArithmeticError FloatingPointE rror ZeroDevisionError AssertionError AttributeError EnvironmentError IOError # OSError EOFError ImportError #
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 126
root of all exc . Ctrl +C , e . g . Program Exit ( sys . exit ()) Base for non - exit exc . only Python 2. x
LookupError IndexError # tupels / lists , e . g . KeyError # dictionaries , e . g . MemoryError NameError # name not found Unbou nd ed Lo calError ReferenceError RuntimeError NotIm pl em en tedError SyntaxError IndentationError TabError SystemError TypeError # type error (2 + "3") ValueError # value errorr ( float (" three ")) UnicodeError UnicodeDec odeErr or UnicodeEnc odeErr or Un i co de T ra ns late E rr or
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 127
Module pickle
Serializing Python objects Save objects as they are (current state) to le
import pickle fd = open ( myObjects , wb ) pickle . dump (x , fd ) pickle . dump (y , fd ) fd . close () Most objects can be pickled Not valid for objects such as opened les
Module pickle
Serializing Python objects Save objects as they are (current state) to le
import pickle fd = open ( myObjects , wb ) pickle . dump (x , fd ) pickle . dump (y , fd ) fd . close () Most objects can be pickled Not valid for objects such as opened les Then load in same order fd = open ( myObjects , rb ) x = pickle . load ( fd ) y = pickle . load ( fd ) fd . close ()
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 129
Misc: Python 2 to 3
Which version to use? See http://wiki.python.org/moin/Python2orPython3 for hints Converting from Python 2.x to Python 3.x
Convert your code to Python 2.6 To check, there is a Py3k warnings mode python -3 scriptname . py
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 130
Misc: Python 2 to 3
Which version to use? See http://wiki.python.org/moin/Python2orPython3 for hints Converting from Python 2.x to Python 3.x
Convert your code to Python 2.6 To check, there is a Py3k warnings mode python -3 scriptname . py If no warnings remain, use 2to3 tool
Misc: Python 2 to 3
Which version to use? See http://wiki.python.org/moin/Python2orPython3 for hints Converting from Python 2.x to Python 3.x
Convert your code to Python 2.6 To check, there is a Py3k warnings mode python -3 scriptname . py If no warnings remain, use 2to3 tool
Ships with Python Converts many things automatically Cant do everything Rest manually
Ships with Python Converts many things automatically Cant do everything Rest manually Further reading: http://docs.python.org/release/3.0.1/library/2to3.html
Tobias Neckel: Scripting with Python... and beyond 130 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 130
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Some modules (urllib, httplib, . . . ) renamed or restructured More views, less lists map ( lambda x : x +1 , l ) filter ( lambda x : x >3 , l ) xrange (10) range (10)
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 131 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 131
list ( map ( lambda x : x +1 , l )) list ( filter (...)) range (10) list ( range (10))
Misc: execle/exec
Run commands
Run/execute commands in current namespace exec ( " a = 3+7 " ) exec ( " print Hello " ) Run/execute commands from le execfile ( filename ) execfile corresponds to run in ipython
code
Use as module
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 132
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 133
code
Use as module
Well built an example, using C++ and swig Provides two functions, computing mod and factorial
int mod ( int x , int y ) { return ( x % y ); } int fact ( int n ) { if ( n <= 1) return 1; else return n * fact (n -1); } /* example . hpp */ // ... int mod ( int x , int y ); int fact ( int n ); // ...
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 133
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 134
Data conversion from C++ to Python Writing both wrapper and interface les
Data conversion from C++ to Python Writing both wrapper and interface les Fortunately, swig (Simplied Wrapper and Interface Generator) does everything for us We only need a .i le:
/* tools . i */ % module tools %{ /* Put header files here ... */ # include " example . hpp " %} /* Parse the header file to generate wrappers */ % include " example . hpp "
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 135
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 135
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 136
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 136
Coments
Using global variables is a little more tricky Functions can be conveniently renamed in the .i le % rename ( __str__ ) DataVector :: toString ;
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 137
Time
Module time Functions to access and display (the current) timestamp Without parameter: use current time
from time import * time () # ctime ([ secs ]) # localtime ([ secs ]) # gmtime ([ secs ]) # # Y, M, D, H, M, S, sleep ( secs ) # secs since 01/01/1970 string ( local time ) struct ( local time ) struct ( GMT ) Wday , Yday , DST (1= y ,0= n , -1=?) pause curr . process
Time
Module time Functions to access and display (the current) timestamp Without parameter: use current time
from time import * time () # ctime ([ secs ]) # localtime ([ secs ]) # gmtime ([ secs ]) # # Y, M, D, H, M, S, sleep ( secs ) # secs since 01/01/1970 string ( local time ) struct ( local time ) struct ( GMT ) Wday , Yday , DST (1= y ,0= n , -1=?) pause curr . process
Measure time (up to 1/100s, system clock dependent) t = time () for i in range (10000): # do something t = time () - t print t , " seconds "
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 138 Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 138
Module Tkinter
Example: Simple window with title # !/ usr / bin / python import Tkinter as tki root = tki . Tk () root . title ( " Hello to all ! " ) tki . Label ( root , text = " Welcome here " , font = " times 32 bold " ). pack () root . mainloop ()
mainloop()
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 139 Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 141
Compressing les
There are modules for tar, zip, bz2, gz, . . .
Compressing les
There are modules for tar, zip, bz2, gz, . . .
Example: module gzip Simple to use: just replace standard call to open
import gzip fd = gzip . open ( " file . txt . gz " , " w " ) fd . write ( """ Funny lines in gzip file """ ) fd . close () fd = gzip . open ( " file . txt . gz " ) print fd . read () fd . close ()
Want to share quickly some les with colleagues in the same network? Goto directory, start python, run three lines, tell them your IP and the port (here: 8000) Thats it!
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 Munchen Scientic Computing in Computer Science, Technische Universitat 143
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 143
Tobias Neckel: Scripting with Python... and beyond Compact Course @ GRS, June 03 - 07, 2013 144