使用pip从列表安装包

时间:2017-08-21 14:00:07

标签: python pip

我正在尝试使用pip安装软件包列表。

我使用的代码是:

import pip

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

此代码工作正常,如果程序包不可用,则会出错:

  

找不到匹配的发行版

但是,我想要做的是如果安装失败(例如:无效的包名),我想打印失败的包。

可以做些什么?

任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:5)

尝试检查非零的返回值,这表示安装时发生错误。并非所有错误都会触发异常。

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)

答案 1 :(得分:3)

您可以检查包的值以验证是否找不到匹配的分发。通常,如果存在安装候选,则包将返回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