Install packages from a list using pip

I am trying to install a list of packages using pip.

The code I use is:

import pip

def install(package_name):
        try:
            pip.main(['install', package_name])
        except:
            print("Unable to install " + package_name)

This code works fine, and if the package is not available, it gives an error:

No matching distributions found

However, what I am trying to do is if the installation fails (for example, an invalid package name), I want to print the failed package.

What can be done for this?

Any help would be appreciated, thanks.

+6
source share
2 answers

Try checking the return value for non-zero, which indicates an error that occurred during installation. Not all errors raise exceptions.

import pip

def install(package_name):
        try:
            pipcode = pip.main(['install', package_name])
            if pipcode != 0:
                print("Unable to install " + package_name + " ; pipcode %d" % pipcode)
        except:
            print("Unable to install " + package_name)
+5
source

, , . 0, , 1

import pip

def install(package_name):
    package = pip.main(['install', package_name])      
    result = "Package successfully installed: " if package == 0 else "Unable to find package: "
    print(result + package_name)

, - :

>>> install("Virtualenvs")

:

Collecting virtualenvs
Could not find a version that satisfies the requirement virtualenvs (from versions: )
No matching distribution found for virtualenvs
Unable to find package: virtualenvs

"Birtualenvs". :

>>> install("virtualenv")

:

Requirement already satisfied: virtualenv in/usr/lib/python2.7/dist-packages
Package successfully installed: virtualenv
+2

All Articles