Python Modules and Packages - Prof. Lotfi Ben Othmane, Study notes of Web Design and Development

An overview of python modules, packages, and standard library modules such as sys, os, fileinput, set, heaps and deques, time, random, shelve, and re. It explains how to develop, use, and explore modules, as well as how to group modules into packages. The document also demonstrates the use of various modules with examples and code snippets.

Typology: Study notes

Pre 2010

Uploaded on 07/28/2009

koofers-user-3zm-1
koofers-user-3zm-1 šŸ‡ŗšŸ‡ø

8 documents

1 / 27

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
3/26/2009 1
Chapter 10: Batteries Included
Lotfi Ben Othmane
Department of Computer Science
Western Michigan University
3/26/2009 2

Modules

Packages

Standard Library
Roadmap
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download Python Modules and Packages - Prof. Lotfi Ben Othmane and more Study notes Web Design and Development in PDF only on Docsity!

3/26/2009 1

Chapter 10: Batteries Included

Lotfi Ben Othmane

Department of Computer Science

Western Michigan University

3/26/2009 2

 Modules

 Packages

 Standard Library

Roadmap

3/26/2009 3

  1. Modules

 Developing Modules

 Using Modules

 Exploring Modules

3/26/2009 4

1.1 Develop Modules

 Modules are python programs. They could be

imported and used in other modules

 Usually modules define functions and classes

 Example of a module containing a function

# hello2.py

# hello2.py

def hello():

def hello():

print "Hello, world!"

print "Hello, world!"

3/26/2009 7

1.2 Using of Modules—Cont.

 To use a module we need to import it then use it

Save a module

3/26/2009 8

1.2 Using of Modules—Cont.

 A module may include code to be executed (e.g.,

call of a function)

# ch10_02.py# ch10_02.py

def hello():def hello():

print "Hello, world!" print "Hello, world!"

hello()hello()

Such module when imported execute specified

Such module when imported execute specified

code (see call to method hello())code (see call to method hello())

The module includes a

call to a function

3/26/2009 9

1.2 Using of Modules—Cont.

 Python uses a variable name. In an imported

module, it is set to the name of the module. If the

module is executed it set to main.

 The technique could be used to run executable

code only when the module is executed and do not

run the code when the module is imported.

# ch10_03.py

# ch10_03.py

def hello():

def hello():

print "Hello, world!"

print "Hello, world!"

if name='main': hello()

if name='main': hello()

Example of code that

tests if a method

should be executed or

not (not executed if the

module is imported)

3/26/2009 10

1.2 Using of Modules—Cont.

 A second method to make a modules available

(could be imported) is to add the folder where the

module is located in the environment variable

PYTHONPATH

 When a module is imported the first time, Python

compiles the program and generates a file with

extension PYC.

 PYC files are machine independent compiled

modules

3/26/2009 13

1.3 Exploring Modules—Cont.

 doc variable could be used to get the

documentation about a function

3/26/2009 14

  1. Packages

 Modules could be grouped in packages

 A package is a directory that includes a set of

modules. It must also include a module with the

name init.py

3/26/2009 15

2. Packages

Exploring package

email

Exploring

init

module for

email

package

3/26/2009 16

3. Standard Library

 sys module

 os module

 fileinput module

 set, heaps and deques modules

 time module

 random module

 shelve module

 re module

3/26/2009 19

3.2 os Module

 Gives access to several operating system services.

 Table below gives an example of variables and

functions available in module os

urandom(n) Returns n bytes of cryptographically strong random data

linesep Line separator ('\n', '\r', or '\r\n')

sep Separator used in paths

system(command) Executes an OS command in a subshell

environ Mapping with environment variables

Function/Variable Description

3/26/2009 20

3.2 os Module--Cont

 Example of use of the module

Variable

TMP

Variable

PCBRAND

3/26/2009 21

3.2 os Module--Cont

 Example of use of the module

Command to

start Firefox

from python

3/26/2009 22

3.3 fileinput Module

 Provides variable and functions that enables iterating

over the lines of a text file

 Table below gives an example of variables and

functions available in module fileinput

close() Closes the sequence

filelineno() Returns line number within current file

lineno() Returns current (cumulative) line number

filename() Returns name of current file

Facilitates iteration over lines in multiple input

streams

input([files[, inplace[,

backup]])

Function/Variable Description

3/26/2009 25

3.4 set, heaps and deques Modules

 Python integrate some data structures such as

dictionary, lists, and string. It includes some modules

for author data structure such as sets, heaps and

deques.

 Sets: constructed from sequence and their main use is

to check membership.

 Heap: kind of priority queue. Let add objects in arbitrary

order. It does some operations with efficiency.

 Deqeue : double-ended queue. Useful when you need

to remove element in the order they were add.

3/26/2009 26

 Example of use of the set module

3.4 set, heaps and deques Modules—

Cont.

3/26/2009 27

 Set of methods for heap operations

3.4 set, heaps and deques Modules—

Cont.

nsmallest(n, iter)

nlargest(n, iter )

heapreplace(heap,x)

heapify(heap)

heappop(heap)

heappush(heap, x)

Function/Variable

Returns the n smallest elements of iter

Returns the n largest elements of iter

Pops off the smallest element and pushes x

Enforces the heap property on an arbitrary list

Pops off the smallest element in the heap

Pushes x onto the heap

Description

3/26/2009 28

3.4 set, heaps and deques Modules—

Cont.

Use of heap module

3/26/2009 31

3.5 time Module—Cont.

 Example of the use of the module

3/26/2009 32

3.6 random Module

 Random module contains functions that return random

numbers, which can be useful for simulations for

example.

sample(seq, n)

shuffle(seq[, random])

choice(seq)

randrange([start], stop,

[step])

uniform(a, b)

random()

Function/Variable

Chooses n random, unique elements from the

sequence seq

Shuffles the sequence seq in place

Returns a random element from the sequence seq

Returns a random number from range(start,

stop,step)

Returns a random real number n such that a ≤ n < b

Returns a random real number n such that 0 ≤ n < 1

Description

3/26/2009 33

3.6 random Module—Cont.

 Example of the use of module random to generate a

random date (ch10_2.py)

from random import *

from time import *

date1 = (2008, 1,21, 0, 0, 0, -1, -1, 0)

time1 = mktime(date1)

date2 = (2009, 1, 11, 0, 0, 0, -1, -1, 0)

time2 = mktime(date2)

randomtime = uniform(time1,time2)

asctime(localtime(randomtime))

3/26/2009 34

3.6 random Module—Cont.

 Example of the use of module random to generate

a random numbers (ch10_3.py)

from random importfrom random import randrangerandrange

num =

num = input('How

input('How many dice? ')

many dice? ')

sides =sides = input('Howinput('How many sides per die? ')many sides per die? ')

sum = 0

sum = 0

for i infor i in range(numrange(num): sum +=): sum += randrange(sidesrandrange(sides) + 1) + 1

print 'The result is', sumprint 'The result is', sum

Output of ch10-3.py

3/26/2009 37

3.7 shelve Module—Cont.

 Simple database application using shelve (ch10_4.py)

import sys, shelve

import sys, shelve

defdef store_person(dbstore_person(db):):

Query user for data and store it in the shelf objectQuery user for data and store it in the shelf object

pidpid == raw_input('Enterraw_input('Enter unique ID number: ')unique ID number: ')

person = {}

person = {}

person['nameperson['name'] ='] = raw_input('Enterraw_input('Enter name: ')name: ')

person['ageperson['age'] ='] = raw_input('Enterraw_input('Enter age: ')age: ')

person['phoneperson['phone'] ='] = raw_input('Enterraw_input('Enter phone number: ')phone number: ')

db[piddb[pid] = person] = person

3/26/2009 38

3.7 shelve Module—Cont.

def

def lookup_person(db

lookup_person(db ):

Query user for ID and desired field, and fetch the corresponQuery user for ID and desired field, and fetch the corresponding datading data

from

from

the shelf objectthe shelf object

pidpid == raw_input('Enterraw_input('Enter ID number: ')ID number: ')

field =field = raw_input('Whatraw_input('What would you like to know? (name, age, phone) ')would you like to know? (name, age, phone) ')

field =field = field.strip().lowerfield.strip().lower()()

printprint field.capitalizefield.capitalize() + ':',() + ':', \

db[pid][fielddb[pid][field]]

defdef print_helpprint_help():():

print 'The available commands are:'print 'The available commands are:'

print 'store : Stores information about a person'

print 'store : Stores information about a person'

print 'lookup : Looks up a person from ID number'print 'lookup : Looks up a person from ID number'

print 'quit : Save changes and exit'

print 'quit : Save changes and exit'

print '? : Prints this message'print '? : Prints this message'

3/26/2009 39

3.7 shelve Module—Cont.

defdef enter_commandenter_command():():

cmdcmd == raw_input('Enterraw_input('Enter command (? for help): ')command (? for help): ')

cmdcmd == cmd.strip().lowercmd.strip().lower()()

return

return cmd

cmd

def main():def main():

database =database = shelve.open('database.datshelve.open('database.dat')')

try:try:

while True:while True:

cmdcmd == enter_commandenter_command()()

ifif cmdcmd == 'store':== 'store':

store_person(database

store_person(database )

elifelif cmdcmd == 'lookup':== 'lookup':

lookup_person(databaselookup_person(database))

elif

elif cmd

cmd == '?':

print_helpprint_help()()

elifelif cmdcmd == 'quit':== 'quit':

returnreturn

finally:finally:

database.close

database.close ()

3/26/2009 40

3.7 shelve Module—Cont.

Example of the use of Ch10_4.py