Home > Articles > Programming > Python

Python Libraries

  • Print
  • + Share This

Python Services

This first group of modules is known as Python Services. These modules provide access to services related to the interpreter and to Python's environment.

sys

The sys module handles system-specific parameters, variables, and functions related to the interpreter.

sys.argv

This object contains the list of arguments that were passed to a program.

If you pass arguments to your program, for example, by saying,

c:\python program.py -a -h -c

you are able to access those arguments by retrieving the value of sys.argv:

>>> import sys
>>> sys.argv
["program.py", "-a", "-h", "-c"]

You can use this list to check whether certain parameters are transported to the interpreter.

>>> If "-h" in sys.argv:
>>>  print "Sorry. There is no help available."

sys.exit()

This is a function used to exit a program. Optionally, it can have a return code. It works by raising the SystemExit exception. If the exception remains uncaught while going up the call stack, the interpreter shuts down.

basic syntax: sys.exit([return_code])

>>> import sys
>>> sys.exit(0)

The return_code argument indicates the return code that should be passed back to the caller application.

The sys module also contains three file objects that take care of the standard input and output devices (see Chapter 1, "Introduction," for more details about these objects).

sys.stdin—File object that is used to read data from the standard input device. Usually it is mapped to the user keyboard.

sys.stdout—File object that is used by every print statement. The default behavior is to output to the screen.

sys.stderr—It stands for standard error output. Usually, it is also mapped to the same object of sys.stdout.

Example:

>>> import sys
>>> data = sys.stdin.readlines()
>>> str = "Counted %d lines." % len(data)
>>> sys.stdout.write (str)

Now, save the previous example in a file named countlines.py, and test it by typing the following instructions on your prompt:

On Unix: cat coutlines.py | python countlines.py
On DOS and Windows: type countlines.py | python countlines.py

sys.modules

It is a dictionary that contains the modules that were loaded by the current session.

sys.platforms

This is a string that shows the current platform (for example, "win32", "mac", _"linux-i386").

You can test which platform is running a program by doing something like this:

if sys.platforms == "win32"
 <do something>
elif sys.platform == "mac"
 <do something else>

sys.path

This is the list of directories that are searched to find the location of a module at the time of importing it.

>>> import.sys
>>> sys.path
['', 'C:\\Program Files\\Python\\Lib\\plat-win',
'C:\\Program Files\\Python\\Lib', 'C:\\Program Files\\Python\\DLLs',
'C:\\Program Files\\Python\\Lib\\lib-tk','C:\\PROGRAM FILES\\PYTHON\\DLLs',
'C:\\PROGRAM FILES\\PYTHON\\lib',
'C:\\PROGRAM FILES\\PYTHON\\lib\\plat-win',
'C:\\PROGRAM FILES\\PYTHON\\lib\\lib-tk',
'C:\\PROGRAM FILES\\PYTHON']

You can easily update this list to include your own directories.

sys.builtin_module_names

This is the list of modules that are not imported as files.

>>> import sys
>>> sys.builtin_module_names
('__builtin__', '__main__', '_locale', '_socket', 'array', 'audioop',
 'binascii', 'cPickle', 'cStringIO', 'cmath', 'errno', 'imageop', 'imp',
 'marshal', 'math', 'md5', 'msvcrt', 'new', 'nt', 'operator', 'pcre',
'regex', 'rgbimg', 'rotor', 'select', 'sha', 'signal', 'soundex', 'strop',
'struct', 'sys', 'thread', 'time', 'winsound')

For all the next sys objects, see Chapter 4, "Exception Handling," for details.

sys.exc_info()

Provides information about the current exception being handled.

sys.exc_type, sys.exc_value, sys.exc_traceback

It is another way to get the information about the current exception being handled.

sys.last_type, sys.last_value and sys.last_traceback

Provides information about the last uncaught exception.

Python 2.0 contains a mode detailed version information function called sys.version_info. This function returns a tuple in the format (major, minor, micro, level, serial). For example, suppose the version number of your Python system is 3.0.4alpha1, the function sys.version_info() returns (3, 0, 4, 'alpha', 1). Note that the level can be one of the following values: alpha, beta, or final.

Another set of functions added to Python 2.0 are: sys.getrecursionlimit() and sys.setrecursionlimit(). These functions are responsible for reading and modifing the maximum recursion depth for the routines in the system. The default value is 1000, and you can run the new script Misc/find_recursionlimit.py in order to know the maximum value suggested for your platform.

types

The types module stores the constant names of the built-in object types.

FunctionType, DictType, ListType, and StringType are examples of the built-in type names.

You can use these constants to find out the type of an object.

>>> import types
>>> if type("Parrot") == types.StringType:
...  print "This is a string!"
...
This is a string

The complete list of built-in object types, that are stored at the types module, can be found in Chapter 5, "Object-Oriented Programming."

UserDict

The UserDict module is a class wrapper that allows you to overwrite or add new methods to dictionary objects.

UserList

The UserList module is a class wrapper that allows you to overwrite or add new methods to list objects.

operator

The operator module stores functions that access the built-in standard operators. The main reason for the operator module is that operator.add, for instance, is much faster than lambda a,b: a+b.

For example, the line

>>> import operator
>>> operator.div(6,2)
3

provides the same result that the next line does.

>>> 6 / 2
3

This module is mostly used when it becomes necessary to pass an operator as the argument of a function. For example

1: import sys, glob, operator
2: sys.argv = reduce(operator.add, map(glob.glob, sys.argv))
3: print sys.argv

To run the previous example, save the code in a file and execute it by switching to your OS prompt and typing:

python yourfilename.py *.*

The heart of this example is Line 2. Let's interpret it:

The glob.glob() function is applied for each element of the original sys.argv list object (by using the map() function). The result is concatenated and reduced into a single variable sys.argv. The concatenation operation is performed by the operator.add() function.

traceback

The traceback module supports print and retrieve operations of the traceback stack. This module is mostly used for debugging and error handling because it enables you to examine the call stack after exceptions have been raised.

See Chapter 4 for more details about this module.

linecache

The linecache module allows you to randomly access any line of a text file.

For example, the next lines of code belong to the file c:\temp\interface.py.

import time, sys
name = raw_input("Enter your name: ")
print "Hi %s, how are you?" % name
feedback = raw_input("What do you want to do now? ")
print "I do not want to do that. Good bye!"
time.sleep(3)
sys.exit()

Check the result that is retrieved when the function linecache.getline(file,linenumber) is called.

>>> import linecache
>>> print linecache.getline("c:\\temp\interface.py",4)
feedback = raw_input("What do you want to do now? ")

pickle

The pickle module handles object serialization by converting Python objects to/from portable strings (byte-streams).

See Chapter 8, "Working with Databases," for details.

cPickle

The cPickle module is a faster implementation of the pickle module.

See Chapter 8 for details.

copy_reg

The copy_reg module extends the capabilities of the pickle and cpickle modules by registering support functions.

See Chapter 8 for details.

shelve

The shelve module offers persistent object storage capability to Python by using dictionary objects. The keys of these dictionaries must be strings and the values can be any object that the pickle module can handle.

See Chapter 8 for more details.

copy

The copy module provides shallow and deep object copying operations for lists, tuples, dictionaries, and class instances.

copy.copy()

This function creates a shallow copy of the x object.

>>> import copy
>>> x = [1, 2, 3, [4, 5, 6]]
>>> y = copy.copy(x)
>>> print y
[1, 2, 3, [4, 5, 6]]
>>> id(y) == id(x)
0

As you can see at the end of the previous example, the new list is not the old one.

As you can see, this function provides the same result that y=x[:] does. It creates a new object that references the old one. If the original object is a mutable object and has its value changed, the new object will change too.

copy.deepcopy()

It recursively copies the entire object. It really creates a new object without any link to the original structure.

basic syntax: variable = copy.deepcopy(object)

>>> import copy
>>> listone = [{"name":"Andre"}, 3, 2]
>>> listtwo = copy.copy(listone)
>>> listthree = copy.deepcopy(listone)
>>> listone[0]["name"] = "Renata"
>>> listone.append("Python")
>>> print listone, listtwo, listthree
[{"name":"Renata"}, 3, 2, "Python"]
[{"name":"Renata"}, 3, 2]
[{"name":"Andre}, 3, 2]

marshal

The marshal module is an alternate method to implement Python object serialization. It allows you to read/write information in a binary format, and convert data to/from character strings. Basically, it is just another way to do byte stream conversions by using serialized Python objects. It is also worth mentioning that marshal is used to serialize code objects for the .pyc files.

This module should be used for simple objects only. Use the pickle module to implement persistent objects in general.

See Chapter 8 for details.

imp

The imp module provides mechanisms to access the internal import statement implementation. You might want to use this module to overload the Python import semantics. Note that the ihooks module provides an easy-to-use interface for this task.

imp.find_module()

This function identifies the physical location of a given module name.

basic syntax: file, path, desc = imp.find_module(modulename)

imp.load_module()

This one loads and returns a module object based on the information provided.

basic syntax: obj = imp.load_module(modulename,file,path,desc)

>>> import imp
>>> def newimport(modulename):
...  file, path, desc = imp.find_module(modulename)
...  moduleobj = imp.load_module(modulename,file,path,desc)
...  return moduleobj
...
... math = newimport(math)
... math.e
2.71828182846

imp.getsuffixes()

It lists the precedence order in which files are imported when using the import statement.

Typing the following commands in my environment accomplishes this:

>>> import imp
>>> imp.get_suffixes()
[('.pyd', 'rb', 3), ('.dll', 'rb', 3), ('.py', 'r', 1), ('.pyc', 'rb', 2)]

Note that if I have a module stored in a file called mymodule.pyc, and I enter the command import mymodule at the interpreter, the system initially searches for a file called mymodule.pyd, and then for one called mymodule.dll, one called mymodule.py, and finally it searches for a file called mymodule.pyc.

TIP

When importing packages, this concept is ignored because directories precede all entries in this list.

parser

The parser module offers you an interface to access Python's internal parser trees and code compiler.

symbol

The symbol module includes constants that represent the numeric values of internal nodes of Python's parse trees. This module is mostly used along with the parser module.

token

The token module is another module that is used along with the parser module. It stores a list of all constants (tokens) that are used by the standard Python tokenizer. These constants represent the numeric values of leaf nodes of the parse trees.

keyword

The keyword module tests whether a string is a Python keyword. Note that the keyword-checking mechanism is not tied to the specific version of Python being used.

keyword.kwlist

This is a list of all Python keywords.

>>> import keyword
>>> keyword.kwlist
['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if',
 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise',
 'return', 'try', 'while']

keyword.iskeyword()

This function tests whether a string is a Python keyword:

>>> import keyword
>>> str = "import"
>>> keyword.iskeyword(str)
1

tokenize

The tokenize module is an analysis tool that provides a lexical scanner for Python source code.

pyclbr

The pyclbr module offers class browser support in order to provide information about classes and methods of a module.

See Chapter 5 for details.

code

The code module interprets base classes, supporting operations that pertain to Python code objects. In other words, it can simulate the standard interpreter's interactive mode.

The next code opens a new interpreter within your interpreter:

>>> import code
>>> interpreter = code.InteractiveConsole()
>>> interpreter.interact()

codeop

The codeop module offers a function to compile Python code. This module is accessed by the code module and shouldn't be used directly.

pprint

The pprint (pretty printer) module prints Python objects so that the interpreter can use them as input for other operations.

>>> import pprint
>>> var = [(1,2,3),"Parrot"]
>>> pprint.pprint(var)
[(1,2,3),"Parrot"]

repr

The repr module is an alternate repr() function implementation that produces object representations that limit the size of resulting strings.

>>> import repr
>>> var = ["Spam" * 10]
>>> print var
['SpamSpamSpamSpamSpamSpamSpamSpamSpamSpam']
>>> print repr.repr(var)
['SpamSpamSpam...mSpamSpamSpam']

py_compile

The py_compile module is a single function that compiles Python source files, generating a byte-code file.

>>> import py_compile
>>> py_compile.compile("testprogram.py")

compileall

The compileall module compiles all Python source files that are stored in a specific directory tree. Note that compileall uses py_compile.

compileall.compile_dir()

This function byte-compiles all source files stored in the provided directory tree.

basic syntax: compile.compile_dir(directory)

>>> import compileall
>>> compileall.compile_dir("c:\\temp")
Listing c:\temp ...
Compiling c:\temp\program3.py ...
Compiling c:\temp\program4.py ...
Compiling c:\temp\program5.py ...
1

dis

The dis module is a Python byte-code dissassembler. This module enables you to analyze Python byte-code.

new

The new module implements a runtime interface that allows you to create various types of objects such as class objects, function objects, instance objects, and so on.

site

The site module performs site-specific packages' initialization. This module is automatically imported during initialization.

user

The user module is a user-specific mechanism that allows one user to have a standard and customized configuration file.

__builtin__

The __builtin__ module is a set of built-in functions that gives access to all _built-in Python identifiers. You don't have to import this module because Python automatically imports it.

Most of the content of this module is listed and explained in the section "Built-In Functions" of Chapter 2, "Language Review."

__main__

The __main__ module is the top-level script environment object in which the interpreter's main program executes. This is how the if __name__ == '__main__' code fragment works.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.