我正在从requirements.txt安装包

pip install -r requirements.txt

requirements.txt文件如下:

Pillow
lxml
cssselect
jieba
beautifulsoup
nltk

LXML是唯一一个安装失败的包,这会导致一切失败(正如larsks在评论中指出的那样,这是预期的结果)。但是,在lxml失败之后,pip仍然运行并下载其余的包。

根据我的理解,如果requirements.txt中列出的任何一个包安装失败,pip install -r requirements.txt命令将失败。

当运行pip install -r requirements.txt时,是否有任何参数可以传递给它,告诉它安装它可以安装的包,跳过它不能安装的包,或者在它看到某些失败时立即退出?


当前回答

Windows:

PIP版本>=18

import sys
from pip._internal import main as pip_main

def install(package):
    pip_main(['install', package])

if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f:
            install(line)

PIP版本<18

import sys
import pip

def install(package):
    pip.main(['install', package])

if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f:
            install(line)

其他回答

谢谢你,艾蒂安·普罗通。

但是,升级到pip 18后,pip包主要不会向公众公开。因此,您可能需要像这样更改代码。

 # This code install line by line a list of pip package 
 import sys
 from pip._internal import main as pip_main

 def install(package):
    pip_main(['install', package])

 if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f:
            install(line)

Windows:

import os
from pip.__main__ import _main as main

error_log = open('error_log.txt', 'w')

def install(package):
    try:
        main(['install'] + [str(package)])
    except Exception as e:
        error_log.write(str(e))

if __name__ == '__main__':
    f = open('requirements1.txt', 'r')
    for line in f:
        install(line)
    f.close()
    error_log.close()

创建一个本地目录,并将requirements.txt文件放在其中。 复制上面的代码,并将其保存为同一个目录中的python文件。记住使用.py扩展名,例如install_packages.py 使用cmd: python install_packages.py运行该文件 所有提到的包都将一次性安装,完全不会停止。:)

您可以在安装函数中添加其他参数。如: Main (['install'] + [str(package)] +['——update'])

Windows:

PIP版本>=18

import sys
from pip._internal import main as pip_main

def install(package):
    pip_main(['install', package])

if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f:
            install(line)

PIP版本<18

import sys
import pip

def install(package):
    pip.main(['install', package])

if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        for line in f:
            install(line)

这个解决方案可以处理requirements.txt中的空行、空格行、#注释行、空格-然后-#注释行。

cat requirements.txt | sed -e '/^\s*#.*$/d' -e '/^\s*$/d' | xargs -n 1 pip install

这是sed魔术的答案。

一行PowerShell:

Get-Content .\requirements.txt | ForEach-Object {pip install $_}

如果你需要忽略某些行,那么:

Get-Content .\ requests .txt | ForEach-Object {if (!$_.startswith("#")){pip install $_}}

OR

Get-Content .\requirements.txt | ForEach-Object {if ($_ -notmatch "#"){pip install $_}}