Home > Articles > Open Source > Python

Python Libraries

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020