我如何知道Python模块是否存在,而不导入它?

导入一些可能不存在(不是我想要的)的东西会导致:

try:
    import eggs
except ImportError:
    pass

当前回答

Go_as的回答是一行:

 python -c "help('modules');" | grep module

其他回答

你可以写一个小脚本,尝试导入所有的模块,并告诉你哪些是失败的,哪些是工作的:

import pip


if __name__ == '__main__':
    for package in pip.get_installed_distributions():
        pack_string = str(package).split(" ")[0]
        try:
            if __import__(pack_string.lower()):
                print(pack_string + " loaded successfully")
        except Exception as e:
            print(pack_string + " failed with error code: {}".format(e))

输出:

zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...

警告一句:这将尝试导入所有内容,因此您将看到类似PyYAML失败的错误代码:没有名为PyYAML的模块,因为实际的导入名称只是yaml。只要知道导入,这个就能帮到你。

Ask Ubuntu的一个更简单的if语句,如何检查Python中是否安装了一个模块?:

import sys
print('eggs' in sys.modules)

如果你知道文件的位置,想要检查相应的Python代码文件是否有该模块,你可以简单地通过Python中的astor包进行检查。这里有一个简单的例子:

"""
Check if a module function exists or not without importing a Python package file
"""
import ast
import astor

tree = astor.parse_file('handler.py')
method_to_check = 'handle'
for item in tree.body:
    if isinstance(item, ast.FunctionDef):
        if item.name == method_to_check:
            print('method exists')
            break

在django.utils.module_loading.module_has_submodule:


import sys
import os
import imp

def module_has_submodule(package, module_name):
    """
    check module in package
    django.utils.module_loading.module_has_submodule
    """
    name = ".".join([package.__name__, module_name])
    try:
        # None indicates a cached miss; see mark_miss() in Python/import.c.
        return sys.modules[name] is not None
    except KeyError:
        pass
    try:
        package_path = package.__path__   # No __path__, then not a package.
    except AttributeError:
        # Since the remainder of this function assumes that we're dealing with
        # a package (module with a __path__), so if it's not, then bail here.
        return False
    for finder in sys.meta_path:
        if finder.find_module(name, package_path):
            return True
    for entry in package_path:
        try:
            # Try the cached finder.
            finder = sys.path_importer_cache[entry]
            if finder is None:
                # Implicit import machinery should be used.
                try:
                    file_, _, _ = imp.find_module(module_name, [entry])
                    if file_:
                        file_.close()
                    return True
                except ImportError:
                    continue
            # Else see if the finder knows of a loader.
            elif finder.find_module(name):
                return True
            else:
                continue
        except KeyError:
            # No cached finder, so try and make one.
            for hook in sys.path_hooks:
                try:
                    finder = hook(entry)
                    # XXX Could cache in sys.path_importer_cache
                    if finder.find_module(name):
                        return True
                    else:
                        # Once a finder is found, stop the search.
                        break
                except ImportError:
                    # Continue the search for a finder.
                    continue
            else:
                # No finder found.
                # Try the implicit import machinery if searching a directory.
                if os.path.isdir(entry):
                    try:
                        file_, _, _ = imp.find_module(module_name, [entry])
                        if file_:
                            file_.close()
                        return True
                    except ImportError:
                        pass
                # XXX Could insert None or NullImporter
    else:
        # Exhausted the search, so the module cannot be found.
        return False

Python 3 >= 3.6: ModuleNotFoundError

ModuleNotFoundError已在Python 3.6中引入,可用于以下目的:

try:
    import eggs
except ModuleNotFoundError:
    # Error handling
    pass

当无法找到模块或其父模块之一时,将引发此错误。所以

try:
    import eggs.sub
except ModuleNotFoundError as err:
    # Error handling
    print(err)

如果找不到eggs模块,将打印类似于No module named 'eggs'的消息;但它会打印类似于没有名为“eggs”的模块。如果子模块找不到,但鸡蛋包可以找到,则Sub '。

有关ModuleNotFoundError的更多信息,请参阅导入系统的文档。