如何编写一个函数来检查模块列表是否存在,否则在 Python 中安装模块

How to write a function to check if a list of modules are present or not, else install modules in Python

我想在 Python 中编写一个 'If Else' 函数来检查模块列表是否存在,否则在 Python (3.6) 中安装模块。

提前致谢!

https://docs.python.org/3/library/sys.html#sys.modules

This is a dictionary that maps module names to modules which have already been loaded.

这是我的做法:

import os
def checkModules(module_list):
    missing = []
    for m in module_list:
        try:
            exec("import %s" % m)
        except ImportError:
            missing.append(m)
    if len(missing) > 0:
        os.system("python -m pip install %s" % ' '.join(missing))

希望对您有所帮助!