Home arrow Python arrow Page 9 - Python 101 (part 7): Dinner With A Hungry Giant

Bucking The System - Python

Python allows developers to logically group functions togetherinto modules, which can be imported and used by any Python program. In thisarticle, find out what a module is, learn how modules and module namespaceswork, and check out the default modules that ship with Python

TABLE OF CONTENTS:
  1. Python 101 (part 7): Dinner With A Hungry Giant
  2. Mercury Rising
  3. Between A Rock And...Another Rock
  4. Love Bytes
  5. Enter The Hungry Giant
  6. From Python, With Love
  7. Doing The Math
  8. String Theory (And Other Interesting Stuff)
  9. Bucking The System
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 5
August 07, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
A special mention should be made here of Python's "sys" module, which allows you to manipulate system-specific parameters like the list of currently-loaded modules and the module search path. The following example demonstrates the important attributes of this module:


>>> import sys >>> # path to python binary >>> sys.executable '/usr/bin/python' >>> # platform >>> sys.platform 'linux-i386' >>> # list of loaded modules >>> sys.modules {'os.path': , 'os': , 'readline': , 'exceptions': , '__main__': , 'posix': , 'sys': , '__builtin__': , 'site': , 'signal': , 'UserDict': , 'posixpath': , 'stat': } >>>


The "path" attribute specifies the search path for modules, and can be modified using standard list constructs.


>>> sys.path ['', '/usr/lib/python1.5/', '/usr/lib/python1.5/plat-linux-i386', '/usr/lib/python1.5/lib-tk', '/usr/lib/python1.5/lib-dynload'] >>> sys.path.append("/usr/local/pymod/") >>> sys.path ['', '/usr/lib/python1.5/', '/usr/lib/python1.5/plat-linux-i386', '/usr/lib/python1.5/lib-tk', '/usr/lib/python1.5/lib-dynload', '/usr/local/pymod/'] >>>


The "argv" attribute contains arguments passed to the program on the command line. Consider the following program:


#!/usr/bin/python

import sys

print "Arguments:"

for x in sys.argv: print x


Here's the output:


$ script.py medusa.server.com vikram 110 Arguments: script.py medusa.server.com vikram 110


As you can see, the first element of the "argv" list contains the name of the called script, with the remaining elements holding the command-line arguments.

Finally, the "__builtin__" module contains information on the various functions that are built into the interpreter. Take a look:


>>> import __builtin__ >>> dir() ['__builtin__', '__builtins__', '__doc__', '__name__'] >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplementedError', 'OSError', 'OverflowError', 'RuntimeError', 'StandardError', 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'buffer', 'callable', 'chr', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dir', 'divmod', 'eval', 'execfile', 'exit', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'str', 'tuple', 'type', 'vars', 'xrange'] >>>


The errors you see are built-in exceptions - we'll be discussing them in detail in the next article.

More information on the various modules which ship with Python is available at http://www.python.org/doc/current/lib/lib.html

And that's about it for this discussion of Python modules. In this article, you found out how to logically group functions together into modules, which are the highest-level abstraction in Python. You examined two different techniques for importing module functions and variables into your own programs, together with the implications of each on your program's namespace. Finally, you found out a little bit more about the default modules that ship with Python, hopefully saving yourself some time the next time you sit down to code a Python program

In the next - and final - article of this series, I will be examining Python's error-handling routines, and demonstrating how to use them to trap and resolve program errors. Make sure that you come back for that one!

Note: All examples in this article have been tested on Linux/i586 with Python 1.5.2. Examples are illustrative only, and are not meant for a production environment. YMMV!

 
 
>>> More Python Articles          >>> More By Vikram Vaswani, (c) Melonfire
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: