Skip to content
Advertisement

How to get a list of all the Python standard library modules?

I want something like sys.builtin_module_names except for the standard library. Other things that didn’t work:

  • sys.modules – only shows modules that have already been loaded
  • sys.prefix – a path that would include non-standard library modules and doesn’t seem to work inside a virtualenv.

The reason I want this list is so that I can pass it to the --ignore-module or --ignore-dir command line options of trace.

So ultimately, I want to know how to ignore all the standard library modules when using trace or sys.settrace.

Advertisement

Answer

Why not work out what’s part of the standard library yourself?

import distutils.sysconfig as sysconfig
import os
std_lib = sysconfig.get_python_lib(standard_lib=True)
for top, dirs, files in os.walk(std_lib):
    for nm in files:
        if nm != '__init__.py' and nm[-3:] == '.py':
            print os.path.join(top, nm)[len(std_lib)+1:-3].replace(os.sep, '.')

gives

abc
aifc
antigravity
--- a bunch of other files ----
xml.parsers.expat
xml.sax.expatreader
xml.sax.handler
xml.sax.saxutils
xml.sax.xmlreader
xml.sax._exceptions

Edit: You’ll probably want to add a check to avoid site-packages if you need to avoid non-standard library modules.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement