【问题标题】:How to write a function to check if a list of modules are present or not, else install modules in Python如何编写一个函数来检查模块列表是否存在,否则在 Python 中安装模块
【发布时间】:2018-07-07 13:12:41
【问题描述】:

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

提前致谢!

【问题讨论】:

标签: python function if-statement python-module


【解决方案1】:

我会这样做:

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

希望有帮助!

【讨论】:

    【解决方案2】:

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

    这是一个字典,将模块名称映射到具有 已经加载了。

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2013-03-03
      • 1970-01-01
      • 2017-09-07
      相关资源
      最近更新 更多