如何验证从包名列表

时间:2016-09-07 21:02:55

标签: python python-2.7 loops import

我正在编写一个程序来安装whl文件中的某些软件包,但是我需要一种方法来验证软件包的安装位置:

def verify_installs(self):
    for pack in self.packages:
        import pip

        installed = pip.get_installed_distributions()

        for name in list(installed):
            if pack not in name:
                print "{} failed to install.".format(pack)

这会抛出错误:

Traceback (most recent call last):
  File "run_setup.py", line 34, in <module>
    test.verify_installs()
  File "run_setup.py", line 29, in verify_installs
    if pack not in name:
TypeError: argument of type 'Distribution' is not iterable

如果我尝试运行包的循环并像这样使用import

def verify_installs(self):
    for pack in self.packages:
        import pack 

我得到错误:

Traceback (most recent call last):
  File "run_setup.py", line 29, in <module>
    test.verify_installs()
  File "run_setup.py", line 24, in verify_installs
    import pack
ImportError: No module named pack

有没有办法可以遍历一个包列表,然后尝试导入它们并捕获导入异常?类似的东西:

def verify_packs(pack_list):
    for pack in pack_list:
        try:
            import pack
        except ImportError:
            print "{} failed to install".format(pack)

2 个答案:

答案 0 :(得分:0)

Say pack_list是模块的字符串名称列表:

import importlib

def verify_packs(pack_list):
    for pack in pack_list:
        try:
            importlib.import_module(pack)
        except ImportError:
            print("{} failed to install".format(pack))

请注意,这不是检查模块是否已安装且可用的首选方法 看看here

答案 1 :(得分:0)

我找到了检查已安装软件包的方法:

def verify_installs(self):
    for pack in self.packages:
        import pip
        items = pip.get_installed_distributions()
        installed_packs = sorted(["{}".format(i.key) for i in items])
        if pack not in installed_packs:
            print "Package {} was not installed".format(pack)

示例:

test = SetUpProgram(["lxml", "test", "testing"], None, None)
test.verify_installs()

输出:

Package test was not installed
Package testing was not installed

现在解释一下,这部分installed_packs = sorted(["{}".format(i.key) for i in items])将创建这个:

['babelfish', 'backports.shutil-get-terminal-size', 'beautifulsoup', 'chardet',
'cmd2', 'colorama', 'cycler', 'decorator', 'django', 'easyprocess', 'gooey', 'gu
essit', 'hachoir-core', 'hachoir-metadata', 'hachoir-parser', 'ipython', 'ipytho
n-genutils', 'lxml', 'matplotlib', 'mechanize', 'mypackage', 'nose', 'numpy', 'p
athlib2', 'pickleshare', 'pillow', 'pip', 'prettytable', 'progressbar', 'prompt-
toolkit', 'pygments', 'pyinstaller', 'pyparsing', 'python-dateutil', 'python-geo
ip', 'python-geoip-geolite2', 'pytz', 'pyvirtualdisplay', 'rebulk', 'requests',
'scapy', 'scrappy', 'selenium', 'setuptools', 'simplegeneric', 'six', 'tinydb',
'traitlets', 'tvdb-api', 'twisted', 'wcwidth', 'win-unicode-console', 'zope.inte
rface']

计算机上所有本地安装的软件包的列表:

if pack not in installed_packs:
    print "Package {} was not installed".format(pack)

将运行包并检查给定列表中的任何包是否与任何实际安装包相对应。