The path list contains a list of directory names where Python
looks for extension modules (Python source modules, compiled modules,
or binary extensions). When you start Python, this list is initialized
from a mixture of built-in rules, the contents of the PYTHONPATH
environment variable, and the registry contents (on Windows). But
since it’s an ordinary list, you can also manipulate it from within
the program:
Example: Using the sys module to manipulate the module search path
# File: `sys-path-example-1.py <sys-path-example-1.py>`__
import sys
print "path has", len(sys.path), "members"
# add the sample directory to the path
sys.path.insert(0, "samples")
import sample
# nuke the path
sys.path = []
import random # oops!
path has 7 members
this is the sample module!
Traceback (innermost last):
File "sys-path-example-1.py", line 11, in ?
import random # oops!
ImportError: No module named random
The builtin_module_names list contains the names of all modules
built into the Python interpreter.
Example: Using the sys module to find built-in modules
# File: `sys-builtin-module-names-example-1.py <sys-builtin-module-names-example-1.py>`__
import sys
def dump(module):
print module, "=>",
if module in sys.builtin_module_names:
print ""
else:
module = __import__(module)
print module.__file__
dump("os")
dump("sys")
dump("string")
dump("strop")
dump("zlib")
os => C:\python\lib\os.pyc
sys =>
string => C:\python\lib\string.pyc
strop =>
zlib => C:\python\zlib.pyd
The modules dictionary contains all loaded modules. The import
statement checks this dictionary before it actually loads something
from disk.
As you can see from the following example, Python loads quite a bunch
of modules before it hands control over to your script.
Example: Using the sys module to find imported modules
# File: `sys-modules-example-1.py <sys-modules-example-1.py>`__
import sys
print sys.modules.keys()
['os.path', 'os', 'exceptions', '__main__', 'ntpath', 'strop', 'nt',
'sys', '__builtin__', 'site', 'signal', 'UserDict', 'string', 'stat']