测试多个软件包的安装

时间:2019-07-02 11:01:19

标签: python python-3.x python-import

作为构建python应用程序(在本例中为Jupyter笔记本)的测试体系的一部分,我想测试系统中安装的所有模块是否将实际加载。

import module from string variable指示我构建以下代码:

    import re
    import subprocess

    s_counter = 0
    f_counter = 0
    errors = []
    libraries = []

    output =  subprocess.run(['conda', 'list'], stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
    for line in output:
        if not re.match('\s*#', line):
            words = re.split('\s+', line)
            if words[0] != 'python':
                libraries.append(words[0])
    for lib in libraries:
        try:
            lib_obj = __import__(lib)
            globals()[lib] = lib_obj
            s_counter += 1
        except ImportError:
            errors.append("ERROR: missing python library: " + lib)
            f_counter += 1
    print(f"Successfuly loaded {s_counter} libraries, failed to load {f_counter}")
    print(f"{errors}")

simplistic 解决方案的问题在于,它假定模块名称与import名称相同。...通常不是。

例如:.... install beautifulsoup4from bs4 import BeautifulSoup

问题是,如何找到模块的import字符串... 以编程方式

0 个答案:

没有答案