How to verify that a package installed from a list of package names
<p>I'm writing a program that will install certain packages from a <code>whl</code> file, however I need a way to verify that the packages where installed:</p>

<pre><code>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)
</code></pre>

<p>This will throw the error:</p>

<pre><code>Traceback (most recent call last):
  File "run_setup.py", line 34, in &lt;module&gt;
    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
</code></pre>

<p>If I attempt to to run a loop of the packages and use <code>import</code> like so:</p>

<pre><code>def verify_installs(self):
    for pack in self.packages:
        import pack 
</code></pre>

<p>I'll get the error:</p>

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

<p>Is there a way I can loop through a list of packages and then try to import them and catch the import exception? Something like:</p>

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

<p>Say <code>pack_list</code> is a list of string names of modules:</p>

<pre><code>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))
</code></pre>

<p>Note that this is not the preferable way to check if a module was installed and available.<br>
Take a look <a href="http://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it">here</a>.</p>

python python-2.7 loops import