Cómo puedo obtener una lista de todos los módulos de la biblioteca estándar de Python


Quiero algo como sys.builtin_module_names excepto por la biblioteca estándar. Otras cosas que no funcionaron:

  • sys.modules - solo muestra los módulos que ya se han cargado
  • sys.prefix - una ruta que incluiría edición de módulos de biblioteca no estándar: y no parece funcionar dentro de un virtualenv.

La razón por la que quiero esta lista es para que pueda pasarla a las opciones de la línea de comandos --ignore-module o --ignore-dir de trace http://docs.python.org/library/trace.html

So en última instancia, quiero saber cómo ignorar todos los módulos de biblioteca estándar cuando se usa trace o sys.settrace.

EDITAR: Quiero que funcione dentro de un virtualenv. http://pypi.python.org/pypi/virtualenv

EDIT2: Quiero que funcione para todos los entornos (es decir, entre sistemas operativos, dentro y fuera de un virtualenv.)

Author: saltycrane, 2011-06-24

7 answers

¿Por qué no averiguar qué es parte de la biblioteca estándar usted mismo?

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('\\','.')

Da

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

Editar: Probablemente querrá agregar una comprobación para evitar site-packages si necesita evitar módulos de biblioteca no estándar.

 9
Author: Caspar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-24 06:11:38

Si alguien sigue leyendo esto en 2015, me encontré con el mismo problema y no me gustó ninguna de las soluciones existentes. Por lo tanto, I brute lo forzó escribiendo algún código para raspar el Índice de la página de la Biblioteca Estándar en los documentos oficiales de Python. También construí una API simple para obtener una lista de bibliotecas estándar (para Python versión 2.6, 2.7, 3.2, 3.3 y 3.4).

El paquete está aquí , y su uso es bastante simple:

>>> from stdlib_list import stdlib_list
>>> libraries = stdlib_list("2.7")
>>> libraries[:10]
['AL', 'BaseHTTPServer', 'Bastion', 'CGIHTTPServer', 'ColorPicker', 'ConfigParser', 'Cookie', 'DEVICE', 'DocXMLRPCServer', 'EasyDialogs']
 24
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 08:43:11

Echa un vistazo a esto, https://docs.python.org/3/py-modindex.html Hicieron una página de índice para los módulos estándar.

 7
Author: Edmund,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-27 17:08:13

Aquí hay una mejora en la respuesta de Caspar, que no es multiplataforma, y se pierde módulos de nivel superior (por ejemplo, email), módulos cargados dinámicamente (por ejemplo, array) y módulos integrados en el núcleo (por ejemplo,.sys):

import distutils.sysconfig as sysconfig
import os
import sys

std_lib = sysconfig.get_python_lib(standard_lib=True)

for top, dirs, files in os.walk(std_lib):
    for nm in files:
        prefix = top[len(std_lib)+1:]
        if prefix[:13] == 'site-packages':
            continue
        if nm == '__init__.py':
            print top[len(std_lib)+1:].replace(os.path.sep,'.')
        elif nm[-3:] == '.py':
            print os.path.join(prefix, nm)[:-3].replace(os.path.sep,'.')
        elif nm[-3:] == '.so' and top[-11:] == 'lib-dynload':
            print nm[0:-3]

for builtin in sys.builtin_module_names:
    print builtin

Esto todavía no es perfecto porque echará de menos cosas como os.path que se define desde dentro de os.py de una manera dependiente de la plataforma a través de código como import posixpath as path, pero es probablemente tan bueno como lo obtendrás, teniendo en cuenta que Python es un lenguaje dinámico y sepa qué módulos están definidos hasta que estén realmente definidos en tiempo de ejecución.

 5
Author: Adam Spiers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 19:42:56

Aquí está una respuesta de 2014 a una pregunta de 2011 -

El autor de isort, una herramienta que limpia las importaciones, tuvo que lidiar con este mismo problema para satisfacer el requisito de pep8 de que las importaciones de la biblioteca central se ordenaran antes que las importaciones de terceros.

He estado usando esta herramienta y parece estar funcionando bien. Puedes usar el método place_module en el archivo isort.py, ya que es de código abierto Espero que al autor no le importe que reproduzca la lógica aquí:

def place_module(self, moduleName):
    """Tries to determine if a module is a python std import, third party import, or project code:

    if it can't determine - it assumes it is project code

    """
    if moduleName.startswith("."):
        return SECTIONS.LOCALFOLDER

    index = moduleName.find('.')
    if index:
        firstPart = moduleName[:index]
    else:
        firstPart = None

    for forced_separate in self.config['forced_separate']:
        if moduleName.startswith(forced_separate):
            return forced_separate

    if moduleName == "__future__" or (firstPart == "__future__"):
        return SECTIONS.FUTURE
    elif moduleName in self.config['known_standard_library'] or \
            (firstPart in self.config['known_standard_library']):
        return SECTIONS.STDLIB
    elif moduleName in self.config['known_third_party'] or (firstPart in self.config['known_third_party']):
        return SECTIONS.THIRDPARTY
    elif moduleName in self.config['known_first_party'] or (firstPart in self.config['known_first_party']):
        return SECTIONS.FIRSTPARTY

    for prefix in PYTHONPATH:
        module_path = "/".join((prefix, moduleName.replace(".", "/")))
        package_path = "/".join((prefix, moduleName.split(".")[0]))
        if (os.path.exists(module_path + ".py") or os.path.exists(module_path + ".so") or
           (os.path.exists(package_path) and os.path.isdir(package_path))):
            if "site-packages" in prefix or "dist-packages" in prefix:
                return SECTIONS.THIRDPARTY
            elif "python2" in prefix.lower() or "python3" in prefix.lower():
                return SECTIONS.STDLIB
            else:
                return SECTIONS.FIRSTPARTY

    return SECTION_NAMES.index(self.config['default_section'])

Obviamente necesita usar este método en el contexto de la clase y el archivo de configuración. Eso es básicamente una alternativa a una lista estática de importaciones de core lib conocidas.

# Note that none of these lists must be complete as they are simply fallbacks for when included auto-detection fails.
default = {'force_to_top': [],
           'skip': ['__init__.py', ],
           'line_length': 80,
           'known_standard_library': ["abc", "anydbm", "argparse", "array", "asynchat", "asyncore", "atexit", "base64",
                                      "BaseHTTPServer", "bisect", "bz2", "calendar", "cgitb", "cmd", "codecs",
                                      "collections", "commands", "compileall", "ConfigParser", "contextlib", "Cookie",
                                      "copy", "cPickle", "cProfile", "cStringIO", "csv", "datetime", "dbhash", "dbm",
                                      "decimal", "difflib", "dircache", "dis", "doctest", "dumbdbm", "EasyDialogs",
                                      "errno", "exceptions", "filecmp", "fileinput", "fnmatch", "fractions",
                                      "functools", "gc", "gdbm", "getopt", "getpass", "gettext", "glob", "grp", "gzip",
                                      "hashlib", "heapq", "hmac", "imaplib", "imp", "inspect", "itertools", "json",
                                      "linecache", "locale", "logging", "mailbox", "math", "mhlib", "mmap",
                                      "multiprocessing", "operator", "optparse", "os", "pdb", "pickle", "pipes",
                                      "pkgutil", "platform", "plistlib", "pprint", "profile", "pstats", "pwd", "pyclbr",
                                      "pydoc", "Queue", "random", "re", "readline", "resource", "rlcompleter",
                                      "robotparser", "sched", "select", "shelve", "shlex", "shutil", "signal",
                                      "SimpleXMLRPCServer", "site", "sitecustomize", "smtpd", "smtplib", "socket",
                                      "SocketServer", "sqlite3", "string", "StringIO", "struct", "subprocess", "sys",
                                      "sysconfig", "tabnanny", "tarfile", "tempfile", "textwrap", "threading", "time",
                                      "timeit", "trace", "traceback", "unittest", "urllib", "urllib2", "urlparse",
                                      "usercustomize", "uuid", "warnings", "weakref", "webbrowser", "whichdb", "xml",
                                      "xmlrpclib", "zipfile", "zipimport", "zlib", 'builtins', '__builtin__'],
           'known_third_party': ['google.appengine.api'],
           'known_first_party': [],

- - - snip - - -

Ya llevaba una hora escribiendo esta herramienta para mí antes de tropezar con el módulo isort, así que espero que esto también pueda ayudar a alguien más a evitar reinventar la rueda.

 3
Author: wim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-09 13:38:42

Esto te acercará:

import sys; import glob
glob.glob(sys.prefix + "/lib/python%d.%d" % (sys.version_info[0:2]) + "/*.py")

Otra posibilidad para la opción ignore-dir:

os.pathsep.join(sys.path)
 2
Author: Keith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-24 06:04:00

Consultaría la referencia estándar de la biblioteca en la documentación oficial, que recorre toda la biblioteca con una sección para cada módulo. :)

 2
Author: Karl Knechtel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-24 07:31:12