简体   繁体   English

使用pip从列表安装包

[英]Installing packages from a list using pip

I am trying to install a list of packages using pip. 我正在尝试使用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 通常,如果存在安装候选,则包将返回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)

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". 因为“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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM