I am trying to install a list of packages using pip.
The code which I used 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 a package is not available, it gives an error:
No matching distributions found
However, what I am trying to do is if an installation fails (for eg: invalid package name), I want to print the package which failed.
What can be done for that?
Any help would be appreciated, thank you.
Try checking the return value for non-zero, which indicates an error occurred with the install. Not all errors trigger 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)
You can check the value of package to verify if no matching distribution was find. Normally the package will return 0 if exists a installation candidate, otherwise will return 1 for no candidate found
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)
So, if you try to do something like this:
>>> install("Virtualenvs")
Will return:
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
Because there's no valid package for "Birtualenvs". But with a valid package:
>>> install("virtualenv")
Will return:
Requirement already satisfied: virtualenv in/usr/lib/python2.7/dist-packages
Package successfully installed: virtualenv