如何获取所有Python标准库模块的列表

时间:2011-06-24 05:47:47

标签: python virtualenv std

除了标准库之外,我想要sys.builtin_module_names之类的东西。其他不起作用的事情:

  • sys.modules - 仅显示已加载的模块
  • sys.prefix - 一个包含非标准库模块EDIT的路径:并且似乎不能在virtualenv中工作。

我想要此列表的原因是我可以将其传递给--ignore-module http://docs.python.org/library/trace.html

--ignore-dirtrace命令行选项

最后,我想知道在使用tracesys.settrace时如何忽略所有标准库模块。

编辑:我想让它在virtualenv中工作。 http://pypi.python.org/pypi/virtualenv

EDIT2:我希望它适用于所有环境(即跨操作系统,在virtualenv的内部和外部。)

8 个答案:

答案 0 :(得分:26)

如果有人在2015年仍在阅读此内容,我遇到了同样的问题,并且不喜欢任何现有的解决方案。所以,我通过编写一些代码来强制它,以便在官方Python文档中删除标准库页面的TOC。我还构建了一个简单的API来获取标准库列表(适用于Python版本2.6,2.7,3.2,3.3和3.4)。

包是here,其用法非常简单:

>>> from stdlib_list import stdlib_list
>>> libraries = stdlib_list("2.7")
>>> libraries[:10]
['AL', 'BaseHTTPServer', 'Bastion', 'CGIHTTPServer', 'ColorPicker', 'ConfigParser', 'Cookie', 'DEVICE', 'DocXMLRPCServer', 'EasyDialogs']

答案 1 :(得分:11)

为什么不自己弄清楚标准库的哪些部分?

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

给出

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

编辑:如果您需要避免使用非标准库模块,您可能需要添加检查以避免site-packages

答案 2 :(得分:7)

看看这个, https://docs.python.org/3/py-modindex.html 他们为标准模块制作了一个索引页。

答案 3 :(得分:6)

这是Caspar答案的改进,它不是跨平台的,并且错过了顶级模块(例如email),动态加载的模块(例如array)和核心内置模块(例如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

这仍然不完美,因为它会遗漏os.path之类的内容,这些内容是通过代码os.py以平台相关方式在import posixpath as path内定义的,但它可能同样出色你会得到的,记住Python是一种动态语言,你不可能真正知道哪些模块是在运行时实际定义的。

答案 4 :(得分:5)

以下是对2011年问题的2014年答案 -

isort的作者,一个清理进口的工具,必须解决同样的问题,以满足pep8要求核心库进口应在第三方进口之前订购。

我一直在使用这个工具,它似乎运作良好。您可以在文件place_module中使用方法isort.py,因为它是开源的我希望作者不介意我在这里复制逻辑:

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'])

显然,您需要在类和设置文件的上下文中使用此方法。这基本上是已知核心lib导入的静态列表的后备。

# 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': [],

---剪辑---

在我偶然发现isort模块之前,我已经花了一个小时为自己编写这个工具,所以我希望这也可以帮助别人避免重新发明轮子!

答案 5 :(得分:4)

在 Python 3.10 上现在有 sys.stdlib_module_names

答案 6 :(得分:2)

这会让你走近:

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

ignore-dir选项的另一种可能性:

os.pathsep.join(sys.path)

答案 7 :(得分:2)

我会参考官方文档中的标准库参考,该文档遍历整个库,每个模块都有一个部分。 :)