Python 模块检测

module_dct = {
    'Matplotlib': 'matplotlib',
    'Numpy': 'numpy',
    'Pandas': 'pandas',
    'Scipy': 'scipy',
    'lxml': 'lxml',
    'selenium': 'selenium',
    'PyMySQL': 'pymysql',
    'requests-html': 'requests_html'
}

def check_module(module_dct):
    import os
    for module_name, import_name in module_dct.items():
        count = 3
        while count:
            try:
                __import__(import_name)
                print('已检测到%s模块' % module_name)
                break
            except ModuleNotFoundError:
                count -= 1
                print('检测到%s未安装,尝试第%d次下载安装' % (module_name, 5 - count))
                command = 'pip install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com ' + module_name
                with os.popen(command, "r") as p:
                    r = p.read()
                    if r.find('Successfully installed %s' % module_name) or r.find('Requirement already satisfied'):
                        break
                    else:
                        continue
posted @ 2020-04-29 02:08  sfdevs  阅读(203)  评论(0)    收藏  举报