检查特定python模块并安装未找到的模块的最有效方法是什么?

2024-04-19 02:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在脚本继续之前检查是否安装了第三方python模块的列表。例如,下面是脚本运行所需的模块列表:

modulesList = ['numpy', 'PIL', 'boto']

我希望脚本检查是否每个模块都已安装,如果没有,则自动安装它们。有没有一种方法可以做到这一点,而不必每次都为列表中的每一项写下我所拥有的?你知道吗

try:
    import foo
except ImportError:
    if extraModules == True:
        os.system(os.path.join(os.path.dirname(sys.executable),'scripts','pip install foo'))
        import foo
    else:
        print 'ERROR: The script cannot run without the foo module installed.\n'
        sys.exit()

Tags: 模块path方法importnumpy脚本列表pil