18.4. Libraries and Common Examples

18.4.1. Modules and Packages

Up to now we have used the core language only, and as usual this is just the tip of the iceberg. Most of the useful functions are hidden in libraries. Python organizes libraries in modules and packages. Modules are just files (with the .py suffix) containing python code (you can also implement modules in C, but this is out of scope of this presentation), and packages are directories containing other modules or packages.

# test.py
def foo(x):
    return 2*x

>>> import test
>>> test.foo(5)
10
>>> from test import foo
>>> foo(3)
6

18.4.2. File I/O

Python's I/O libraries were developed as an abstraction of the UNIX system. File objects are input/output streams which can be created from files, sockets, and in memory strings. Here are some examples:

>>> f = open("test.txt", "w")
>>> for name in ["Joe", "John", "Mary"]:
	f.write("my name is %s\n" % name)
>>> f.close()
>>> open("test.txt").read()
'my name is Joe\nmy name is John\nmy name is Mary\n'
>>> for line in open("test.txt"):
	print "line:", line.strip()
line: my name is Joe
line: my name is John
line: my name is Mary

18.4.3. Regular Expressions

No scripting language can succeed without a sophisticated regular expression library. Python's (second) regular expression module is modeled after Perl's killer feature, but uses a plain object based interface.

>>> import re
>>> pattern = re.compile("hello[ \t]*(.*)")
>>> match = pattern.match("hello world")
>>> match
<_sre.SRE_Match object at 0x0145A190>
>>> match.group(1)
'world'
>>> match.group(0)
'hello world'
>>> pattern.match("bla")
>>> print pattern.match("bla")
None

18.4.4. SQL Database Access

After some time, Python now also provides a standard interface for the access to an SQL database including drivers for the most common databases (Oracle, Sybase, PostgreSQL, mySQL, SAP DB, etc.).

>>> import sys, psycopg
>>> connection = psycopg.connect(
       "host=127.0.0.1 user=test password=test dbname=testdb")
>>> cursor = conn.cursor()
>>> try:
        cursor.execute("create table person (firstname varchar(20), lastname varchar(20))")
        cursor.execute("insert into person values ('Homer', 'Simpson')")
        cursor.execute("select * from person")
        print cursor.fetchall()
    finally:
        curs.execute("drop table person")