



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 27
This page cannot be seen from the preview
Don't miss anything!




















3/26/2009 1
3/26/2009 2
3/26/2009 3
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
3/26/2009 7
1.2 Using of ModulesāCont.
To use a module we need to import it then use it
3/26/2009 8
1.2 Using of ModulesāCont.
A module may include code to be executed (e.g.,
call of a function)
Such module when imported execute specified
Such module when imported execute specified
code (see call to method hello())code (see call to method hello())
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.
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
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
3/26/2009 16
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
3/26/2009 21
3.2 os Module--Cont
Example of use of the module
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.
3/26/2009 28
3.4 set, heaps and deques Modulesā
Cont.
3/26/2009 31
3/26/2009 32
3/26/2009 33
3.6 random ModuleāCont.
Example of the use of module random to generate a
random date (ch10_2.py)
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
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.