Python: List Modules, Search Path, Loaded Modules

By Xah Lee. Date: . Last updated: .

List Available Modules

To list all modules, type pydoc modules in terminal.

or in Python

print (help('modules') )

# -*- coding: utf-8 -*-

# prints a list of existing modules
print(help('modules'))
Please wait a moment while I gather a list of all available modules...

CDROM               binhex              itertools           site
DLFCN               bisect              json                sitecustomize
IN                  builtins            keyword             smtpd
TYPES               bz2                 lib2to3             smtplib
...

Note: in Ubuntu Linux, as of , there's a bug that both pydoc modules and help('modules') will crash Python. Use python3 instead.

sudo apt-get install python3

pydoc3 modules

Reading Module Documentation

To read the doc of a module, in terminal, type pydoc module_name, or in Python program call help(module_name).

# -*- coding: utf-8 -*-
# python

import os

# print the module's online manual
print help(os)

2. Built-in Functions — Python v2.7.6 documentation #help

Note: the documentation from pydoc is not identical to the official documentation. Doc from pydoc is generated from the module source code, and is terse and technical.

List Module's Function/Variable Names

# -*- coding: utf-8 -*-
# python

import re

# print all names exported by the module
print dir(re)

# sample output:

# ['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_locale', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']

2. Built-in Functions — Python v2.7.6 documentation #dir

27.3. __builtin__ — Built-in objects — Python v2.7.6 documentation #module-__builtin__

Using Module

import module_name → load a module.

module_name.function_name → call a function in module.

# -*- coding: utf-8 -*-
# python

# import the standard module named os

import os

# example of using a function
print 'current dir is:', os.getcwd()

Import Function Names from Module

Module's function name can be imported directly by the syntax:

# -*- coding: utf-8 -*-
# python

from os import getcwd
print getcwd()  # current working dir

6. Simple statements — Python v2.7.6 documentation #import

5. Built-in Types — Python v2.7.6 documentation #modules

Default “module”

All global (variable/function) names in Python are considered to be in the pseudo-module namespace named __main__.

# -*- coding: utf-8 -*-
# python

print dir() # ['__builtins__', '__doc__', '__file__', '__name__', '__package__']

print dir("__main__")

# ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

27.5. __main__ — Top-level script environment — Python v2.7.6 documentation #module-__main__

Module Search Paths

Python module search paths is stored in the variable sys.path.

# -*- coding: utf-8 -*-
# python

import sys
import pprint

# pretty print module search paths
pprint.pprint(sys.path)

# sample output
"""
['/home/jane/web/',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/python2.7/dist-packages/gst-0.10',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
 '/usr/lib/python2.7/dist-packages/ubuntuone-couch',
 '/usr/lib/python2.7/dist-packages/ubuntuone-installer',
 '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
"""

27.1. sys — System-specific parameters and functions — Python v2.7.6 documentation #sys.path

List Loaded Modules

Loaded module names is stored in the variable sys.modules.

# -*- coding: utf-8 -*-
# python

import sys
import pprint

# pretty print loaded modules
pprint.pprint(sys.modules)

# sample output
"""
{'UserDict': <module 'UserDict' from '/usr/lib/python2.7/UserDict.pyc'>,
 '__builtin__': <module '__builtin__' (built-in)>,
 '__main__': <module '__main__' from '/home/jane/web/test.py'>,
 '_abcoll': <module '_abcoll' from '/usr/lib/python2.7/_abcoll.pyc'>,
 '_codecs': <module '_codecs' (built-in)>,
 '_sre': <module '_sre' (built-in)>,
 '_warnings': <module '_warnings' (built-in)>,
 '_weakref': <module '_weakref' (built-in)>,
 '_weakrefset': <module '_weakrefset' from '/usr/lib/python2.7/_weakrefset.pyc'>,
 'abc': <module 'abc' from '/usr/lib/python2.7/abc.pyc'>,
 'apport_python_hook': <module 'apport_python_hook' from '/usr/lib/python2.7/dist-packages/apport_python_hook.pyc'>,
 'cStringIO': <module 'cStringIO' (built-in)>,
 'codecs': <module 'codecs' from '/usr/lib/python2.7/codecs.pyc'>,
 'copy_reg': <module 'copy_reg' from '/usr/lib/python2.7/copy_reg.pyc'>,
 'encodings': <module 'encodings' from '/usr/lib/python2.7/encodings/__init__.pyc'>,
 'encodings.__builtin__': None,
 'encodings.aliases': <module 'encodings.aliases' from '/usr/lib/python2.7/encodings/aliases.pyc'>,
 'encodings.codecs': None,
 'encodings.encodings': None,
 'encodings.utf_8': <module 'encodings.utf_8' from '/usr/lib/python2.7/encodings/utf_8.pyc'>,
 'errno': <module 'errno' (built-in)>,
 'exceptions': <module 'exceptions' (built-in)>,
 'genericpath': <module 'genericpath' from '/usr/lib/python2.7/genericpath.pyc'>,
 'linecache': <module 'linecache' from '/usr/lib/python2.7/linecache.pyc'>,
 'os': <module 'os' from '/usr/lib/python2.7/os.pyc'>,
 'os.path': <module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>,
 'posix': <module 'posix' (built-in)>,
 'posixpath': <module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>,
 'pprint': <module 'pprint' from '/usr/lib/python2.7/pprint.pyc'>,
 're': <module 're' from '/usr/lib/python2.7/re.pyc'>,
 'signal': <module 'signal' (built-in)>,
 'site': <module 'site' from '/usr/lib/python2.7/site.pyc'>,
 'sitecustomize': <module 'sitecustomize' from '/usr/lib/python2.7/sitecustomize.pyc'>,
 'sre_compile': <module 'sre_compile' from '/usr/lib/python2.7/sre_compile.pyc'>,
 'sre_constants': <module 'sre_constants' from '/usr/lib/python2.7/sre_constants.pyc'>,
 'sre_parse': <module 'sre_parse' from '/usr/lib/python2.7/sre_parse.pyc'>,
 'stat': <module 'stat' from '/usr/lib/python2.7/stat.pyc'>,
 'sys': <module 'sys' (built-in)>,
 'sysconfig': <module 'sysconfig' from '/usr/lib/python2.7/sysconfig.pyc'>,
 'traceback': <module 'traceback' from '/usr/lib/python2.7/traceback.pyc'>,
 'types': <module 'types' from '/usr/lib/python2.7/types.pyc'>,
 'warnings': <module 'warnings' from '/usr/lib/python2.7/warnings.pyc'>,
 'zipimport': <module 'zipimport' (built-in)>}
"""

27.1. sys — System-specific parameters and functions — Python v2.7.6 documentation #sys.modules

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help

String

  1. Quote String
  2. String Operations
  3. String Methods
  4. Format String

Branching, Loop

  1. True, False
  2. if then else
  3. for, while, Loops

List

  1. List Basics
  2. Loop Thru List
  3. Map Function to List
  4. List Comprehension
  5. List Methods

Dictionary

  1. Dictionary
  2. Loop Thru Dictionary
  3. Dictionary Methods

Function

  1. Function Parameter

Class

  1. Class and Object

Module

  1. List Modules
  2. Write a Module

Unicode

  1. Python + Unicode 🐍
  2. Process Unicode
  3. Convert File Encoding

Common Tasks

  1. Read/Write File
  2. Traverse Directory
  3. Complex Numbers
  4. Get Env Var
  5. JSON

Regex

  1. Regex Basics
  2. Split Line by Regex
  3. Regex Reference

Advanced

  1. Copy Nested List
  2. Tuple vs List
  3. Sets, Union, Intersection
  4. Closure in Python 2
  5. Decorator
  6. Append String in Loop
  7. Timing Functions with timeit
  8. Keyword Argument Default Value Unstable
  1. Find Python Script Path
  2. Manipulate Path
  3. Sort Matrix, Object

Find/Replace

  1. Find/Replace Strings on Multiple Files
  2. Find/Replace Multi-line Strings in a Dir
  3. Find/Replace Mulitple Pairs of Strings
  4. Find/Replace by Regex
  5. Find/Replace Strings in Unicode Files
  6. Python, Perl: Find/Replace Strings in a File

HTML/Web

  1. Sending Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  1. A Script to check HTML file size
  2. Thumbnail Generation

Misc

  1. System Call
  2. Decompress Gzip

reference