标签归档:pip

升级pip后出错:无法导入名称“ main”

问题:升级pip后出错:无法导入名称“ main”

每当我尝试使用pip安装任何软件包时,都会收到此导入错误:

guru@guru-notebook:~$ pip3 install numpy
Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'


guru@guru-notebook:~$ cat `which pip3`
#!/usr/bin/python3
# GENERATED BY DEBIAN

import sys

# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.
from pip import main
if __name__ == '__main__':
    sys.exit(main())

之前它运行良好,我不确定为什么会引发此错误。我已经搜索了此错误,但找不到任何可解决的错误。

如果您需要更多详细信息,请告诉我,我将更新我的问题。

Whenever I am trying to install any package using pip, I am getting this import error:

guru@guru-notebook:~$ pip3 install numpy
Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'


guru@guru-notebook:~$ cat `which pip3`
#!/usr/bin/python3
# GENERATED BY DEBIAN

import sys

# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.
from pip import main
if __name__ == '__main__':
    sys.exit(main())

It was working fine earlier, I am not sure why it is throwing this error. I have searched about this error, but can’t find anything to fix it.

Please let me know if you need any further detail, I will update my question.


回答 0

您必须不经意间升级了系统pip(可能通过sudo pip install pip --upgrade

pip 10.x调整其内部位置。pip3您看到的命令是您的软件包维护者提供的(这里大概是基于debian的?),而不是pip管理的文件。

您可以在pip的问题跟踪器上了解有关此内容的更多信息

你可能会想升级系统PIP和改为使用的virtualenv。

要恢复pip3二进制文件,您需要sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

如果您想继续在“不受支持的地区”(在系统软件包管理器之外升级系统软件包),则可以选择使用python3 -m pip ...代替pip3

You must have inadvertently upgraded your system pip (probably through something like sudo pip install pip --upgrade)

pip 10.x adjusts where its internals are situated. The pip3 command you’re seeing is one provided by your package maintainer (presumably debian based here?) and is not a file managed by pip.

You can read more about this on pip’s issue tracker

You’ll probably want to not upgrade your system pip and instead use a virtualenv.

To recover the pip3 binary you’ll need to sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall.

If you want to continue in “unsupported territory” (upgrading a system package outside of the system package manager), you can probably get away with python3 -m pip ... instead of pip3.


回答 1

我们可以通过修改pip文件来清除错误。

检查文件的位置:

$ which pip

路径-> / usr / bin / pip

转到该位置(/ usr / bin / pip)并打开终端

输入: $ sudo nano pip

您可以看到:

import sys
from pip import main
if __name__ == '__main__':
     sys.exit(main())

改成:

import sys
from pip import __main__
if __name__ == '__main__':
     sys.exit(__main__._main())

然后按Ctrl + o写入更改并退出

希望能做到!

We can clear the error by modifying the pip file.

Check the location of the file:

$ which pip

path -> /usr/bin/pip

Go to that location(/usr/bin/pip) and open terminal

Enter: $ sudo nano pip

You can see:

import sys
from pip import main
if __name__ == '__main__':
     sys.exit(main())

Change to:

import sys
from pip import __main__
if __name__ == '__main__':
     sys.exit(__main__._main())

then ctrl + o write the changes and exit

Hope this will do!!


回答 2

对于Ubuntu系列,Debian和Linux Mint用户

多亏了Anthony的上述说明,您可以保留原始系统pip(位于/ usr / bin /和dist-packages /中)并删除手动安装的pip(位于〜/ .local /中)以解决冲突:

$ python3 -m pip uninstall pip

来自python3-pipdebian软件包的Ubuntu / Debian pip v8.1.1(16.04)(请参阅参考资料$ pip3 -V)显示的搜索结果与最新的pip v10.0.1相同,并且可以从PyPI安装最新的模块。它具有有效的pip命令(已在$ PATH中),以及--user自2016年以来默认修补的nice 选项。查看pip发行说明,较新的版本主要是针对用例特定的错误修复和某些新功能,因此不是每个人都必须赶紧升级点子。无论如何,新的pip 10可以部署到Python virtualenvs。

但是,无论使用哪种pip,您的操作系统都可以通过APT快速安装常见的Python模块(包括numpy),而无需使用pip,例如:(
$ sudo apt install python3-numpy python3-scipy具有系统依赖性)
$ sudo apt install python3-pip(Debian修补的pip,稍旧,但是没关系)

快速apt语法提醒(请参阅man apt有关详细信息):(
$ sudo apt update以从最新源重新同步Ubuntu软件包索引文件)
$ apt search <python-package-name> (对所有可用软件包进行全文搜索)
$ apt show <python-package-name>(显示详细的软件包说明)
$ sudo apt install <python-package-name>

前缀python-为的软件包名称适用于Python 2;并带有前缀python3-用于Python 3(例如python3-pandas)。有成千上万个,它们在Debian和Ubuntu中进行集成测试。除非您寻求在每个用户级别(pip install --user选件)或在virtualenv / venv中安装,否则可能会需要apt。这些系统程序包也可以从虚拟环境访问,因为如果您的环境没有给定模块的副本,则virtualenv将在使用时优雅地转而使用系统库。您自定义安装的(带有pip --user)每用户模块~/.local/lib也会覆盖它们。

请注意,由于这是系统范围的安装,因此您几乎不需要删除它们(需要注意OS依赖性)。这对于具有许多系统依赖性的软件包(例如,使用scipy或matplotlib)很方便,因为APT会跟踪并提供所有必需的系统库和C扩展名,而使用pip则无法保证

实际上,对于系统范围的Python软件包(与按用户,主目录级别或更低级别的软件包相反),Ubuntu 希望使用APT软件包管理器(而不是sudo pip)来避免破坏OS:sudo pip3/usr/lib/python3/dist-packagesAPT存储OS的同一目录为目标敏感模块。Debian / Ubuntu的最新发行版在很大程度上依赖于Python 3,因此其预装模块由apt且不应该更改。

因此,如果您使用pip3 install命令,请确保它在隔离的虚拟开发环境中运行,例如virtualenvsudo apt install python3-virtualenv)或Python3内置(-m venv)或在每个用户级别运行(--userpip选项,在Ubuntu提供的默认选项中自2016年以来一直是pip),但不是系统范围的(从来没有sudo pip3!),因为pip会干扰 APT软件包管理器的操作,并且在意外更改系统使用的python模块时可能会影响Ubuntu OS 组件。祝好运!


P. S. 以上都是针对“理想”解决方案的(Debian / Ubuntu方式)。

如果您仍然想独占使用新的pip3 v10,则有3种快速解决方法:

  • 只需打开一个新的bash会话(一个新的终端选项卡,或键入bash)-pip3 v10可用(请参阅参考资料pip3 -V)。debian的pip3 v8仍然安装但已损坏;要么
  • $ hash -d pip3 && pip3 -V 用于刷新$ PATH中的pip3路径名的命令。debian的pip3 v8仍然安装但已损坏;要么
  • 该命令$ sudo apt remove python3-pip && hash -d pip3用于完全卸载debian的pip3 v8,以支持新的pip3 v10。

注意:--user除非您处于virtualenv中,否则您将始终需要将标记添加到任何非debian提供的pip中!(~/.local/自2016年起,它将python软件包部署到,默认为debian / ubuntu提供的python3-pip和python-pip)。Ubuntu / Debian并不真正支持您在virtualenv之外使用系统范围内的pip 10。永不sudo pip3

更多详细信息:
https : //github.com/pypa/pip/issues/5221#issuecomment-382069604
https://github.com/pypa/pip/issues/5240#issuecomment-381673100

For Ubuntu family, Debian, Linux Mint users

Thanks to Anthony’s explanation above, you can retain your original system pip (in /usr/bin/ and dist-packages/) and remove the manually-installed pip (in ~/.local/) to resolve the conflict:

$ python3 -m pip uninstall pip

Ubuntu/Debian pip v8.1.1 (16.04) from python3-pip debian package (see$ pip3 -V) shows the same search results as the latest pip v10.0.1, and installs latest modules from PyPI just fine. It has a working pip command (already in the $PATH), plus the nice --user option patched-in by default since 2016. Looking at pip release notes, the newer versions are mostly about use-case specific bug fixes and certain new features, so not everyone has to rush upgrading pip just yet. And the new pip 10 can be deployed to Python virtualenvs, anyway.

But regardless of pips, your OS allows to quickly install common Python modules (including numpy) with APT, without the need for pip, for example:
$ sudo apt install python3-numpy python3-scipy (with system dependencies)
$ sudo apt install python3-pip (Debian-patched pip, slightly older but it doesn’t matter)

Quick apt syntax reminder (please see man apt for details):
$ sudo apt update (to resync Ubuntu package index files from up-to-date sources)
$ apt search <python-package-name> (full text-search on all available packages)
$ apt show <python-package-name> (displays the detailed package description)
$ sudo apt install <python-package-name>

Package names prefixed with python- are for Python 2; and prefixed with python3- are for Python 3 (e.g. python3-pandas). There are thousands, and they undergo integration testing within Debian and Ubuntu. Unless you seek to install at per-user level (pip install --user option) or within virtualenv/venv, apt could be what you needed. These system packages are accessible from virtual envs too, as virtualenv will gracefully fall back to using system libs on import if your envs don’t have given copies of modules. Your custom-installed (with pip --user) per-user modules in ~/.local/lib will override them too.

Note, since this is a system-wide installation, you’d rarely need to remove them (need to be mindful about OS dependencies). This is convenient for packages with many system dependencies (such as with scipy or matplotlib), as APT will keep track and provide all required system libs and C extensions, while with pip you have no such guarantees.

In fact, for system-wide Python packages (in contrast to per-user, home dir level, or lower), Ubuntu expects using the APT package manager (rather than sudo pip) to avoid breaking OS: sudo pip3 targets the very same /usr/lib/python3/dist-packages directory where APT stores OS-sensitive modules. Recent Debian/Ubuntu releases depend heavily on Python 3, so its pre-installed modules are managed by apt and shouldn’t be changed.

So if you use pip3 install command, please ensure that it runs in an isolated virtual dev environment, such as with virtualenv (sudo apt install python3-virtualenv), or with Python3 built-in (-m venv), or at a per-user level (--user pip option, default in Ubuntu-provided pip since 2016), but not system-wide (never sudo pip3!), because pip interferes with the operation of the APT package manager and may affect Ubuntu OS components when a system-used python module is unexpectedly changed. Good luck!


P. S. All the above is for the ‘ideal’ solution (Debian/Ubuntu way).

If you still want to use the new pip3 v10 exclusively, there are 3 quick workarounds:

  • simply open a new bash session (a new terminal tab, or type bash) – and pip3 v10 becomes available (see pip3 -V). debian’s pip3 v8 remains installed but is broken; or
  • the command $ hash -d pip3 && pip3 -V to refresh pip3 pathname in the $PATH. debian’s pip3 v8 remains installed but is broken; or
  • the command $ sudo apt remove python3-pip && hash -d pip3 to uninstall debian’s pip3 v8 completely, in favor of your new pip3 v10.

Note: You will always need to add --user flag to any non-debian-provided pip, unless you are in a virtualenv! (it deploys python packages to ~/.local/, default in debian/ubuntu-provided python3-pip and python-pip since 2016). Your use of pip 10 system-wide, outside of virtualenv, is not really supported by Ubuntu/Debian. Never sudo pip3!

Further details:
https://github.com/pypa/pip/issues/5221#issuecomment-382069604
https://github.com/pypa/pip/issues/5240#issuecomment-381673100


回答 3

仅一步解决。

我也曾经遇到过这个问题,但是可以简单地通过1条命令解决它,而不会打扰和浪费时间,而且我已经在多个系统上进行了尝试,这是解决此问题的最干净的方法。那就是:

对于python3:- sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

这样,您可以简单地使用安装软件包pip3。检查使用pip3 --version

对于旧版本,请使用:sudo python -m pip uninstall pip && sudo apt install python-pip --reinstall

这样,您现在可以使用来简单地安装软件包pip。检查使用pip --version

resolved in one step only.

I too faced this issue, But this can be resolved simply by 1 command without bothering around and wasting time and i have tried it on multiple systems it’s the cleanest solution for this issue. And that’s:

For python3:- sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall.

By this , you can simply install packages using pip3. to check use pip3 --version.

For older versions, use : sudo python -m pip uninstall pip && sudo apt install python-pip --reinstall.

By this, now you can simply install packages using pip. to check use pip --version.


回答 4

使用python -m pip install代替pip install

例:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

pip(相应地pip3)执行是由你的发行版提供的(python-pip在Ubuntu 16.04封装)和位于/usr/bin/pip

因此,pip在升级pip时,它不会与软件包本身保持最新状态,并且可能会损坏。

如果您只是python -m pip直接使用,例如:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

它会通过您的Python路径,找到最新版本的pip并执行该文件。

它依赖于这样的事实,即文件可以通过来执行import,但这是一种非常标准的接口类型,因此比骇客的Debian脚本更不可能被破坏。

然后,我建议将以下别名添加到您的.bashrc

pip() ( python -m pip "$@" )
pip3() ( python3 -m pip "$@" )

Ubuntu 18.04 /usr/bin/pip3文件执行以下操作:

from pip import main

大概mainpip在某个时候被破坏了。

中断的pip提交似乎是:95bcf8c5f6394298035a7332c441868f3b0169f4“将所有内部API移至pip._internal”已进入pip 18.0。

pip39.0.1升级到18.0 后,在Ubuntu 16.04中进行了测试。

pyenv

但是,最终,对于认真的Python开发,我只建议您使用pyenv + virtualenv安装自己的本地Python,这也可以解决以下Ubuntu错误:https ://askubuntu.com/questions/682869/how-do-i- 安装一个不同的python-version-using-apt-get / 1195153#1195153

Use python -m pip install instead of pip install

Example:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

The pip (resp. pip3) executable is provided by your distro (python-pip package on Ubuntu 16.04) and located at /usr/bin/pip.

Therefore, it is not kept up-to date with the pip package itself as you upgrade pip, and may break.

If you just use python -m pip directly, e.g. as in:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

it goes through your Python path, finds the latest version of pip and executes that file.

It relies on the fact that file is executable through import, but that is a very standard type of interface, and therefore less likely to break than the hackier Debian script.

Then I recommend adding the following aliases to your .bashrc:

pip() ( python -m pip "$@" )
pip3() ( python3 -m pip "$@" )

The Ubuntu 18.04 /usr/bin/pip3 file does:

from pip import main

and presumably main was removed from pip at some point which is what broke things.

The breaking pip commit appears to be: 95bcf8c5f6394298035a7332c441868f3b0169f4 “Move all internal APIs to pip._internal” which went into pip 18.0.

Tested in Ubuntu 16.04 after an update from pip3 9.0.1 to 18.0.

pyenv

Ultimately however, for serious Python development I would just recommend that you install your own local Python with pyenv + virtualenv, which would also get around this Ubuntu bug: https://askubuntu.com/questions/682869/how-do-i-install-a-different-python-version-using-apt-get/1195153#1195153


回答 5

您可以通过重新安装pip解决此问题。

使用以下命令行命令之一重新安装pip:

Python2:

python -m pip uninstall pip && sudo apt install python-pip --reinstall

Python3:

 python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

You can resolve this issue by reinstalling pip.

Use one of the following command line commands to reinstall pip:

Python2:

python -m pip uninstall pip && sudo apt install python-pip --reinstall

Python3:

 python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

回答 6

检查pip是否已缓存在另一路径上,为此,请调用$ which pip并检查该路径是否与错误中提示的路径不同(如果是这种情况):

$ hash -r

清除缓存后,pip将再次起作用。参考:http : //cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory

Check if pip has been cached on another path, to do so, call $ which pip and check that the path is different from the one prompted in the error, if that’s the case run:

$ hash -r

When the cache is clear, pip will be working again. reference: http://cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory


回答 7

我在有sudo apt但没有sudo pip的系统上运行。(并且没有su访问权限。)我按照pip的建议进入了同样的情况:

您正在使用pip版本8.1.1,但是18.0可用。您应该考虑通过“ pip install –upgrade pip”命令进行升级。

没有其他修复程序对我有用,因为我没有足够的管理员权限。但是,通过阅读以下内容,我有些不安:

  • 我不应该这样做 当然,点子告诉我。撒谎了
  • 使用–user通过专注于仅用户目录解决了许多问题。

因此,我发现此命令行可以将我恢复到原来的状态。如果您使用的版本与8.1.1不同,则显然需要更改该行的该部分。

python -m pip install --force-reinstall pip==8.1.1 --user

那是唯一对我有用的东西,但是效果很好!

I’m running on a system where I have sudo apt but no sudo pip. (And no su access.) I got myself into this same situation by following the advice from pip:

You are using pip version 8.1.1, however 18.0 is available. You should consider upgrading via the ‘pip install –upgrade pip’ command.

None of the other fixes worked for me, because I don’t have enough admin privileges. However, a few things stuck with me from reading up on this:

  • I shouldn’t have done this. Sure, pip told me to. It lied.
  • Using –user solves a lot of issues by focusing on the user-only directory.

So, I found this command line to work to revert me back to where I was. If you were using a different version than 8.1.1, you will obviously want to change that part of the line.

python -m pip install --force-reinstall pip==8.1.1 --user

That’s the only thing that worked for me, but it worked perfectly!


回答 8

使用python3 -m pip install --user pip==9.0.1(或可用的版本)进行恢复

Recover with python3 -m pip install --user pip==9.0.1 (or the version that worked)


回答 9

使用新的LXC(strech)在Pixelbook上发生了同样的事情。此解决方案与公认的解决方案非常相似,只是有一个细微的区别,即我固定了pip3。

sudo python3 -m pip install --upgrade pip

颠覆了版本,现在可以正常工作了。

我在这里找到了它。Python.org:确保pip是最新的

Same thing happened to me on Pixelbook using the new LXC (strech). This solution is very similar to the accepted one, with one subtle difference, whiched fixed pip3 for me.

sudo python3 -m pip install --upgrade pip

That bumped the version, and now it works as expected.

I found it here … Python.org: Ensure pip is up-to-date


回答 10

我在Ubuntu 16.04系统上遇到了相同的问题。我设法通过使用以下命令重新安装pip来修复它:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

I met the same problem on my Ubuntu 16.04 system. I managed to fix it by re-installing pip with the following command:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3


回答 11

上面的命令对我不起作用,但这些命令非常有用:

sudo apt purge python3-pip
sudo rm -rf '/usr/lib/python3/dist-packages/pip'  
sudo apt install python3-pip
cd
cd .local/lib/python3/site-packages
sudo rm -rf pip*  
cd
cd .local/lib/python3.5/site-packages
sudo rm -rf pip*  
sudo pip3 install jupyter

The commands above didn’t work for me but those were very helpful:

sudo apt purge python3-pip
sudo rm -rf '/usr/lib/python3/dist-packages/pip'  
sudo apt install python3-pip
cd
cd .local/lib/python3/site-packages
sudo rm -rf pip*  
cd
cd .local/lib/python3.5/site-packages
sudo rm -rf pip*  
sudo pip3 install jupyter

回答 12

在ubuntu 18.04.1 Bionic Beaver中,您需要注销并重新登录(无需重新启动)以获得正确的环境。

$ sudo apt install python-pip

$ pip --version
pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7)

$ pip install --upgrade pip

$ pip --version
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

$ exit
<login>

$ pip --version
pip 18.1 from /home/test/.local/lib/python2.7/site-packages/pip (python 2.7)

In ubuntu 18.04.1 Bionic Beaver, you need to log out and log back in (restart not necessary) to get the proper environment.

$ sudo apt install python-pip

$ pip --version
pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7)

$ pip install --upgrade pip

$ pip --version
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

$ exit
<login>

$ pip --version
pip 18.1 from /home/test/.local/lib/python2.7/site-packages/pip (python 2.7)

回答 13

我用 sudo apt remove python3-pip 然后pip工作。

 ~ sudo pip install pip --upgrade
[sudo] password for sen: 
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'
  ~ sudo apt remove python3-pip   
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libexpat1-dev libpython3-dev libpython3.5-dev python-pip-whl python3-dev python3-wheel
  python3.5-dev
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
  python3-pip
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 569 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 215769 files and directories currently installed.)
Removing python3-pip (8.1.1-2ubuntu0.4) ...
Processing triggers for man-db (2.7.5-1) ...
  ~ pip

Usage:   
  pip <command> [options]

I use sudo apt remove python3-pip then pip works.

 ~ sudo pip install pip --upgrade
[sudo] password for sen: 
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'
➜  ~ sudo apt remove python3-pip   
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libexpat1-dev libpython3-dev libpython3.5-dev python-pip-whl python3-dev python3-wheel
  python3.5-dev
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
  python3-pip
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 569 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 215769 files and directories currently installed.)
Removing python3-pip (8.1.1-2ubuntu0.4) ...
Processing triggers for man-db (2.7.5-1) ...
➜  ~ pip

Usage:   
  pip <command> [options]

回答 14

对于Python 2.7版,@ Anthony解决方案可以完美实现,方法是将python3更改为python,如下所示:

sudo python -m pip uninstall pip && sudo apt install python-pip --reinstall

For Python version 2.7 @Anthony solution works perfect, by changing python3 to python as follows:

sudo python -m pip uninstall pip && sudo apt install python-pip --reinstall

回答 15

对我来说使用修复错误的原因pip3是:

sudo cp -v /usr/local/bin/pip3 /usr/bin/pip3

一切正常:

 demon@UbuntuHP:~$ pip -V
 pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

 demon@UbuntuHP:~$ pip2 -V
 pip 10.0.1 from /home/demon/.local/lib/python2.7/site-packages/pip (python 2.7)

 demon@UbuntuHP:~$ pip3 -V
 pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

也许新的10.0.1版本的pip不会更新/ usr / bin中的二进制文件?(似乎没有)

编辑:在Ubuntu 18.04中会发生相同的问题。我发现的最佳解决方案是将pip二进制文件从符号链接/home/<user/.local/bin/usr/local/bin/usr/bin(取决于您的偏好),如下所示:

ln -sv /home/<user>/.local/bin/pip /usr/local/bin/pip
ln -sv /home/<user>/.local/bin/pip2 /usr/local/bin/pip2
ln -sv /home/<user>/.local/bin/pip2.7 /usr/local/bin/pip2.7
ln -sv /home/<user>/.local/bin/pip3 /usr/local/bin/pip3
ln -sv /home/<user>/.local/bin/pip3.6 /usr/local/bin/pip3.6

注意:替换 <user> 为当前运行的用户

关联的版本(最新)位于:

版本3.6:

/home/demon/.local/lib/python3.6/site-packages/pip(python 3.6)

2.7版:

/home/demon/.local/lib/python2.7/site-packages/pip(python 2.7)

What worked for me to fix the error with using pip3 was:

sudo cp -v /usr/local/bin/pip3 /usr/bin/pip3

Everything works:

 demon@UbuntuHP:~$ pip -V
 pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

 demon@UbuntuHP:~$ pip2 -V
 pip 10.0.1 from /home/demon/.local/lib/python2.7/site-packages/pip (python 2.7)

 demon@UbuntuHP:~$ pip3 -V
 pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

Maybe the new 10.0.1 version of pip doesn’t update the binary in /usr/bin ? (which seems it does not)

EDIT: the same issue occurs in Ubuntu 18.04. The best solution I’ve found is to symlink the pip binaries from /home/<user/.local/bin to /usr/local/bin or /usr/bin (depending on your preference), as follows:

ln -sv /home/<user>/.local/bin/pip /usr/local/bin/pip
ln -sv /home/<user>/.local/bin/pip2 /usr/local/bin/pip2
ln -sv /home/<user>/.local/bin/pip2.7 /usr/local/bin/pip2.7
ln -sv /home/<user>/.local/bin/pip3 /usr/local/bin/pip3
ln -sv /home/<user>/.local/bin/pip3.6 /usr/local/bin/pip3.6

NOTE: replace <user> with your current running user

The associated versions (latest) are in:

Version 3.6:

/home/demon/.local/lib/python3.6/site-packages/pip (python 3.6)

Version 2.7:

/home/demon/.local/lib/python2.7/site-packages/pip (python 2.7)


回答 16

绝招

须藤-H pip install lxml

Trick and works too

sudo -H pip install lxml


回答 17

我也遇到了同样的错误,但python -m pip仍在工作,因此我使用了核选项解决了该问题sudo python -m pip install --upgrade pip。它为我做到了。

I had this same error, but python -m pip was still working, so I fixed it with the nuclear option sudo python -m pip install --upgrade pip. It did it for me.


回答 18

对于它的价值,我遇到了pip(不是pip2pip3)问题:

$ pip -V
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

$ pip2 -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)

$ pip3 -V
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

不知何故(我不记得如何),我在~/.local目录中安装了python东西。从那里删除pip目录后,pip再次开始工作。

$ rm -rf /home/precor/.local/lib/python2.7/site-packages/pip
$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)

For what it’s worth, I had the problem with pip (not pip2 or pip3):

$ pip -V
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

$ pip2 -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)

$ pip3 -V
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

Somehow (I can’t remember how) I had python stuff installed in my ~/.local directory. After I removed the pip directory from there, pip started working again.

$ rm -rf /home/precor/.local/lib/python2.7/site-packages/pip
$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)

回答 19

软件包有问题,当它生成文件/ usr / bin / pip时,必须更改导入:

from pip import main

from pip._internal import main

这就解决了问题,我不确定它为什么产生,但是在以下问题中说得很对:

在pyenv上进行pip 10升级后,“导入错误:无法导入名称’main’”

Is something wrong with the packages, when it generating de file /usr/bin/pip, you have to change the import:

from pip import main

to

from pip._internal import main

That solves the problem, I’m not sure why it generated, but it saids somthing in the following issue:

After pip 10 upgrade on pyenv “ImportError: cannot import name ‘main'”


回答 20

您可以尝试以下方法:

sudo ln -sf $( type -P pip ) /usr/bin/pip

You can try this:

sudo ln -sf $( type -P pip ) /usr/bin/pip

回答 21

当我想将系统pip pip3从9.0.1 升级到19.2.3 时,我也遇到了这个问题。

运行后pip3 install --upgrade pippip版本变为19.2.3。但main()已移至pip._internal最新版本,但已pip3损坏。

因此,在文件中/usr/bin/pip3,替换line 9from pip import mainfrom pip._internal import main。该问题将得到解决,适用于python2-pip。(在Ubuntu 18.04发行版上测试)

根据@Vincent H.的回答

I also run into this problem when I wanted to upgrade system pip pip3 from 9.0.1 to 19.2.3.

After running pip3 install --upgrade pip, pip version becomes 19.2.3. But main() has been moved in pip._internal in the latest version, which leaves pip3 broken.

So in file /usr/bin/pip3, replace line 9: from pip import main with from pip._internal import main. The issue will be fixed, works the same for python2-pip. (Tested on Ubuntu 18.04 distribution)

According to @Vincent H.’s answer


回答 22

请运行以下命令进行修复。运行后python3 -m pip install --upgrade pip,请运行以下命令。

hash -r pip

资料来源:https : //github.com/pypa/pip/issues/5221

Please run the following commands to do the fix. After running python3 -m pip install --upgrade pip, please run the following command.

hash -r pip

Source: https://github.com/pypa/pip/issues/5221


回答 23

您可以简单地使用以下方法修复pip和pip3路径 update-alternatives

您应该检查的第一件事是当前$PATH 运行情况,echo $PATH然后您可以找到/usr/local/binpip3和pip通常在哪里

有一个变化,您的系统正在这里寻找/bin/pip/bin/pip3 所以我会说通过添加到您的~/.bash_profile文件中使其持久存在

export PATH=$PATH:/usr/local/bin 然后用which pip和检查它是否固定which pip3

如果没有update-alternatives,最后用它来修复

update-alternatives --install /bin/pip3 pip3 /usr/local/bin/pip3 30

如果您想将pip指向pip3,则

update-alternatives --install /bin/pip pip /usr/local/bin/pip3 30

you can simply fix the pip and pip3 paths using update-alternatives

first thing you should check is your current $PATH run echo $PATH and see is you can find /usr/local/bin which is where pip3 and pip usually are

there is a change your system is looking here /bin/pip and /bin/pip3 so i will say fix the PATH by adding to your ~/.bash_profile file so it persists

export PATH=$PATH:/usr/local/bin and then check is its fixed with which pip and which pip3

if not then use update-alternatives to fix it finally

update-alternatives --install /bin/pip3 pip3 /usr/local/bin/pip3 30

and if you want to point pip to pip3 then

update-alternatives --install /bin/pip pip /usr/local/bin/pip3 30

回答 24

这对我有用!

hash -r pip # or hash -d pip

现在,卸载pip安装的版本,然后使用以下命令将其重新安装。

python -m pip uninstall pip  # sudo
sudo apt install --reinstall python-pip

如果pip损坏,请使用:

python -m pip install --force-reinstall pip

希望能帮助到你!

This Worked for me !

hash -r pip # or hash -d pip

Now, uninstall the pip installed version and reinstall it using the following commands.

python -m pip uninstall pip  # sudo
sudo apt install --reinstall python-pip

If pip is broken, use:

python -m pip install --force-reinstall pip

Hope it helps!


回答 25

从pip._internal导入main

from pip._internal import main

编辑来自的点子代码

sudo nano /usr/bin/pip3

import main from pip._internal

from pip._internal import main

Edit the pip code from

sudo nano /usr/bin/pip3

回答 26

正如@cryptoboy所说的-检查您安装了什么pip / python版本

 demon@UbuntuHP:~$ pip -V
 demon@UbuntuHP:~$ pip2 -V
 demon@UbuntuHP:~$ pip3 -V

然后在.local / lib /文件夹中检查不需要的库。

当我迁移到较新的Kubuntu时,我做了设置的备份,并且在主目录中有.local / lib / python2.7 /文件夹。安装了python 3.6。我刚刚删除了旧文件夹,现在一切正常!

As @cryptoboy said – check what pip/python version you have installed

 demon@UbuntuHP:~$ pip -V
 demon@UbuntuHP:~$ pip2 -V
 demon@UbuntuHP:~$ pip3 -V

and then check for no-needed libraries in your .local/lib/ folder.

I did backup of settings when I was migrating to newer Kubuntu and in had .local/lib/python2.7/ folder in my home directory. Installed python 3.6. I just removed the old folder and now everything works great!


回答 27

在Debian上,您需要先更新apt。

sudo apt-get update -qq
sudo apt-get install python-pip -qq
sudo pip install pip --upgrade --quiet
sudo pip2 install virtualenv --quiet

如果您跳过“ sudo apt-get update -qq”,则您的点会损坏并显示“找不到主要”错误。

On Debian you will need to update apt first….

sudo apt-get update -qq
sudo apt-get install python-pip -qq
sudo pip install pip --upgrade --quiet
sudo pip2 install virtualenv --quiet

If you skip ‘sudo apt-get update -qq’ your pip will become corrupt and display the ‘cannot find main’ error.


回答 28

此错误可能是权限错误。因此,测试使用-H标志执行命令:

sudo -H pip3 install numpy

This error may be a permission one. So, test executing the command with -H flag:

sudo -H pip3 install numpy

回答 29

在执行任何pip命令之前使用以下命令

hash -d pip

会工作的

Use the following command before the execution of any pip command

hash -d pip

It will work


没有名为pkg_resources的模块

问题:没有名为pkg_resources的模块

我正在将Django应用程序部署到开发服务器,并且在运行时遇到此错误pip install -r requirements.txt

Traceback (most recent call last):
  File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

pkg_resources似乎与一起分发setuptools。最初,我认为可能不会将它安装到virtualenv中的Python,所以我setuptools 2.6使用以下命令将了(与Python相同的版本)安装到virtualenv 中的Python站点软件包中:

sh setuptools-0.6c11-py2.6.egg --install-dir /var/www/mydir/virtualenvs/dev/lib/python2.6/site-packages

编辑:这只发生在virtualenv内部。如果我在virtualenv之外打开控制台,则pkg_resources存在,但仍然出现相同的错误。

关于为什么pkg_resources不在路上的任何想法?

I’m deploying a Django app to a dev server and am hitting this error when I run pip install -r requirements.txt:

Traceback (most recent call last):
  File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

pkg_resources appears to be distributed with setuptools. Initially I thought this might not be installed to the Python in the virtualenv, so I installed setuptools 2.6 (same version as Python) to the Python site-packages in the virtualenv with the following command:

sh setuptools-0.6c11-py2.6.egg --install-dir /var/www/mydir/virtualenvs/dev/lib/python2.6/site-packages

EDIT: This only happens inside the virtualenv. If I open a console outside the virtualenv then pkg_resources is present, but I am still getting the same error.

Any ideas as to why pkg_resources is not on the path?


回答 0

2018年7月更新

现在大多数人都应该使用pip install setuptools(可能与一起使用sudo)。

有些人可能需要(重新)安装python-setuptools通过他们的软件包管理的软件包(apt-get installyum install,等)。

此问题可能高度取决于您的操作系统和开发环境。如果上述方法不适用于您,请参见下面的旧式/其他答案。

说明

此错误消息是由缺少/损坏的Python setuptools软件包引起的。根据Matt M.的注释和setuptools问题#581,以下引用的引导脚本不再是推荐的安装方法。

如果仍然对任何人有帮助,引导脚本说明将保留在下面。

旧版答案

ImportError今天在尝试使用点子时遇到了同样的问题。不知何故,该setuptools软件包已在我的Python环境中删除。

要解决此问题,请运行以下安装脚本setuptools

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

(或者,如果您尚未wget安装(例如OS X),请尝试

curl https://bootstrap.pypa.io/ez_setup.py | python

可能带有sudo前缀。)

如果您使用的任何版本distribute,或setuptools0.6以下的版本,则必须先将其卸载。*

有关更多详细信息,请参见安装说明


*如果您已经可以使用distribute,则将其升级到“兼容性包装器” setuptools可以更轻松地进行切换。但是,如果事情已经坏了,请不要尝试。

July 2018 Update

Most people should now use pip install setuptools (possibly with sudo).

Some may need to (re)install the python-setuptools package via their package manager (apt-get install, yum install, etc.).

This issue can be highly dependent on your OS and dev environment. See the legacy/other answers below if the above isn’t working for you.

Explanation

This error message is caused by a missing/broken Python setuptools package. Per Matt M.’s comment and setuptools issue #581, the bootstrap script referred to below is no longer the recommended installation method.

The bootstrap script instructions will remain below, in case it’s still helpful to anyone.

Legacy Answer

I encountered the same ImportError today while trying to use pip. Somehow the setuptools package had been deleted in my Python environment.

To fix the issue, run the setup script for setuptools:

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

(or if you don’t have wget installed (e.g. OS X), try

curl https://bootstrap.pypa.io/ez_setup.py | python

possibly with sudo prepended.)

If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.*

See Installation Instructions for further details.


* If you already have a working distribute, upgrading it to the “compatibility wrapper” that switches you over to setuptools is easier. But if things are already broken, don’t try that.


回答 1

sudo apt-get install --reinstall python-pkg-resources

在Debian中为我修复了该问题。似乎卸载某些.deb软件包(在我的情况下为扭曲集)已破坏python用于查找软件包的路径

sudo apt-get install --reinstall python-pkg-resources

fixed it for me in Debian. Seems like uninstalling some .deb packages (twisted set in my case) has broken the path python uses to find packages


回答 2

尝试在Ubuntu 13.10上将rhodecode安装到virtualenv时,我已经看到此错误。对我来说,解决方案是运行

pip install --upgrade setuptools
pip install --upgrade distribute 

在运行easy_install rhodecode之前。

I have seen this error while trying to install rhodecode to a virtualenv on ubuntu 13.10. For me the solution was to run

pip install --upgrade setuptools
pip install --upgrade distribute 

before I run easy_install rhodecode.


回答 3

这也发生在我身上。我认为,在virtualenv使用setuptools的情况下,如果requirements.txt包含“ distribute”条目,则会出现此问题。Pip将尝试修补setuptools以便为分发腾出空间,但不幸的是,它将失败一半。

一种简单的解决方案是删除当前的virtualenv,然后使用–distribute参数创建一个新的virtualenv。

如果使用virtualenvwrapper的示例:

$ deactivate
$ rmvirtualenv yourenv
$ mkvirtualenv yourenv --distribute
$ workon yourenv
$ pip install -r requirements.txt

It also happened to me. I think the problem will happen if the requirements.txt contains a “distribute” entry while the virtualenv uses setuptools. Pip will try to patch setuptools to make room for distribute, but unfortunately it will fail half way.

The easy solution is delete your current virtualenv then make a new virtualenv with –distribute argument.

An example if using virtualenvwrapper:

$ deactivate
$ rmvirtualenv yourenv
$ mkvirtualenv yourenv --distribute
$ workon yourenv
$ pip install -r requirements.txt

回答 4

在CentOS 6中,安装软件包python-setuptools对其进行了修复。

yum install python-setuptools

In CentOS 6 installing the package python-setuptools fixed it.

yum install python-setuptools

回答 5

我之前有这个错误,评分最高的答案给我一个错误,试图下载ez_setup.py文件。我找到了另一个来源,因此您可以运行以下命令:

curl http://peak.telecommunity.com/dist/ez_setup.py | python

我发现还必须使用sudo它才能使其正常工作,因此您可能需要运行:

sudo curl http://peak.telecommunity.com/dist/ez_setup.py | sudo python

我还创建了另一个位置,可以从以下位置下载脚本:

https://gist.github.com/ajtrichards/42e73562a89edb1039f3

I had this error earlier and the highest rated answer gave me an error trying to download the ez_setup.py file. I found another source so you can run the command:

curl http://peak.telecommunity.com/dist/ez_setup.py | python

I found that I also had to use sudo to get it working, so you may need to run:

sudo curl http://peak.telecommunity.com/dist/ez_setup.py | sudo python

I’ve also created another location that the script can be downloaded from:

https://gist.github.com/ajtrichards/42e73562a89edb1039f3


回答 6

在尝试了以下几个答案之后,与一位同事联系,在Ubuntu 16.04上为我工作的是:

pip install --force-reinstall -U setuptools
pip install --force-reinstall -U pip

就我而言,只有枕头3.1.1的旧版本有问题(枕头4.x正常工作),现在已解决!

After trying several of these answers, then reaching out to a colleague, what worked for me on Ubuntu 16.04 was:

pip install --force-reinstall -U setuptools
pip install --force-reinstall -U pip

In my case, it was only an old version of pillow 3.1.1 that was having trouble (pillow 4.x worked fine), and that’s now resolved!


回答 7

需要更多的须藤。然后使用easy_install安装pip。作品。

sudo wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
sudo easy_install pip

Needed a little bit more sudo. Then used easy_install to install pip. Works.

sudo wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
sudo easy_install pip

回答 8

我通过执行以下操作修复了virtualenv的错误:

从复制了pkg_resources.py

/Library/Python/2.7/site-packages/setuptools

/Library/Python/2.7/site-packages/

这可能是一个便宜的解决方法,但对我有用。

如果不存在安装工具,则可以通过键入尝试安装系统站点软件包virtualenv --system-site-packages /DESTINATION DIRECTORY,将最后一部分更改为要安装到的目录。pkg_rousources.py将在lib / python2.7 / site-packages中的该目录下

I fixed the error with virtualenv by doing this:

Copied pkg_resources.py from

/Library/Python/2.7/site-packages/setuptools

to

/Library/Python/2.7/site-packages/

This may be a cheap workaround, but it worked for me.

.

If setup tools doesn’t exist, you can try installing system-site-packages by typing virtualenv --system-site-packages /DESTINATION DIRECTORY, changing the last part to be the directory you want to install to. pkg_rousources.py will be under that directory in lib/python2.7/site-packages


回答 9

对我来说,导致此错误是因为我有一个名为“ site”的子目录!我不知道这是否是pip错误,但我从以下内容开始:

/some/dir/requirements.txt / some / dir / site /

pip install -r requirements.txt无法正常工作,出现上述错误!

将子文件夹从“ site”重命名为“ src”解决了该问题!也许pip正在寻找“网站包装”?疯。

For me, this error was being caused because I had a subdirectory called “site”! I don’t know if this is a pip bug or not, but I started with:

/some/dir/requirements.txt /some/dir/site/

pip install -r requirements.txt wouldn’t work, giving me the above error!

renaming the subfolder from “site” to “src” fixed the problem! Maybe pip is looking for “site-packages”? Crazy.


回答 10

当我将我的virtualenv激活为不同于创建它的用户时,我遇到了这个问题。看来是权限问题。我在尝试@cwc的答案时发现了这一点,并在输出中看到了这一点:

Installing easy_install script to /path/env/bin
error: /path/env/bin/easy_install: Permission denied

切换回创建virtualenv的用户,然后运行原始pip install命令没有任何问题。希望这可以帮助!

I had this problem when I had activated my virtualenv as a different user than the one who created it. It seems to be a permission problem. I discovered this when I tried the answer by @cwc and saw this in the output:

Installing easy_install script to /path/env/bin
error: /path/env/bin/easy_install: Permission denied

Switching back to the user that created the virtualenv, then running the original pip install command went without problems. Hope this helps!


回答 11

我今天也有这个问题。我只在虚拟环境中遇到问题。

对我来说,解决方案是停用虚拟环境,删除后再使用pip卸载virtualenv并重新安装。之后,我为我的项目创建了一个新的虚拟环境,然后pip在虚拟环境中都能正常工作,就像在正常环境中一样。

I had this problem today as well. I only got the problem inside the virtual env.

The solution for me was deactivating the virtual env, deleting and then uninstalling virtualenv with pip and reinstalling it. After that I created a new virtual env for my project, then pip worked fine both inside the virtual environment as in the normal environment.


回答 12

看起来他们已经离开了bitbucket,现在在github(https://github.com/pypa/setuptools)上

运行的命令是:

wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python

Looks like they have moved away from bitbucket and are now on github (https://github.com/pypa/setuptools)

Command to run is:

wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python

回答 13

对我来说,原来是上的权限问题site-packages。由于这只是我的开发环境,因此我提出了权限,然后一切又重新开始了:

sudo chmod -R a+rwx /path/to/my/venv/lib/python2.7/site-packages/

For me, it turned out to be a permissions problem on site-packages. Since it’s only my dev environment, I raised the permissions and everything is working again:

sudo chmod -R a+rwx /path/to/my/venv/lib/python2.7/site-packages/

回答 14

如果通过conda安装的应用程序遇到此问题,则解决方案(如此错误报告中所述)仅是使用以下命令安装安装工具:

conda install setuptools

If you are encountering this issue with an application installed via conda, the solution (as stated in this bug report) is simply to install setup-tools with:

conda install setuptools

回答 15

在Windows上,使用python 3.7,这对我有用:

pip install --upgrade setuptools --user

--user 将软件包安装在您的主目录中,该目录不需要管理员权限。

On Windows, with python 3.7, this worked for me:

pip install --upgrade setuptools --user

--user installs packages in your home directory, which doesn’t require admin privileges.


回答 16

简单的解决方法是您可以使用conda升级setuptools或整个环境。(特别适用于Windows用户。)

conda upgrade -c anaconda setuptools

如果删除了setuptools,则需要再次安装setuptools。

conda install -c anaconda setuptools

如果所有方法均无效,则可以升级conda环境。但是我不建议您需要重新安装和卸载某些软件包,因为这样做会加剧这种情况。

the simple resoluition is that you can use conda to upgrade setuptools or entire enviroment. (Specially for windows user.)

conda upgrade -c anaconda setuptools

if the setuptools is removed, you need to install setuptools again.

conda install -c anaconda setuptools

if these all methodes doesn’t work, you can upgrade conda environement. But I do not recommend that you need to reinstall and uninstall some packages because after that it will exacerbate the situation.


回答 17

显然您缺少setuptools。某些virtualenv版本默认情况下使用分发而不是setuptools。--setuptools在创建virtualenv时使用该选项,或者VIRTUALENV_SETUPTOOLS=1在您的环境中设置。

Apparently you’re missing setuptools. Some virtualenv versions use distribute instead of setuptools by default. Use the --setuptools option when creating the virtualenv or set the VIRTUALENV_SETUPTOOLS=1 in your environment.


回答 18

就我而言,我最初安装了2个python版本,后来又删除了较旧的版本。因此,在创建虚拟环境时

virtualenv venv

指的是卸载的python

什么对我有用

python3 -m virtualenv venv

当您尝试使用点子时也是如此。

In my case, I had 2 python versions installed initially and later I had deleted the older one. So while creating the virtual environment

virtualenv venv

was referring to the uninstalled python

What worked for me

python3 -m virtualenv venv

Same is true when you are trying to use pip.


回答 19

当我尝试遵循本OSX指南时,遇到了这个答案。对我python get-pip有用的是,跑步后,我还必须easy_install pip。这解决了根本无法运行点子的问题。我确实安装了一堆旧的Macport东西。那可能有冲突。

I came across this answer when I was trying to follow this guide for OSX. What worked for me was, after running python get-pip, I had to ALSO easy_install pip. That fixed the issue of not being able to run pip at all. I did have a bunch of old macport stuff installed. That may have conflicted.


回答 20

在Windows上,我安装了从www.lfd.uci.edu/~gohlke/pythonlibs/下载的pip然后出现了这个问题。

所以我应该先安装setuptools(easy_install)。

On windows, I installed pip downloaded from www.lfd.uci.edu/~gohlke/pythonlibs/ then encontered this problem.

So I should have installed setuptools(easy_install) first.


回答 21

只需setuptools通过以下方式重新安装您的:

$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefefe74e
$ tar -zxvf setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11/
$ sudo python setup.py build
$ sudo python setup.py install
$ sudo pip install --upgrade setuptools

那么一切都会好起来的。

just reinstall your setuptools by :

$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefefe74e
$ tar -zxvf setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11/
$ sudo python setup.py build
$ sudo python setup.py install
$ sudo pip install --upgrade setuptools

then everything will be fine.


回答 22

我使用CentOS 6.7,而我的python刚刚从2.6.6升级到2.7.11,在尝试了许多不同的答案之后,终于有以下一个工作了:

sudo yum install python-devel

希望能帮助同样情况的人。

I use CentOS 6.7, and my python was just upgrade from 2.6.6 to 2.7.11, after tried so many different answer, finally the following one does the job:

sudo yum install python-devel

Hope help someone in the same situation.


回答 23

没有一个发布的答案对我有用,所以我重新安装了pip并成功了!

sudo apt-get install python-setuptools python-dev build-essential 

sudo easy_install pip 

pip install --upgrade setuptools

(参考:http//www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/

None of the posted answers worked for me, so I reinstalled pip and it worked!

sudo apt-get install python-setuptools python-dev build-essential 

sudo easy_install pip 

pip install --upgrade setuptools

(reference: http://www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/)


回答 24

更新我的Ubuntu版本后,我遇到了这个问题。它似乎已经遍历并删除了我所有虚拟环境中的设置工具。

为了解决这个问题,我将虚拟环境重新安装回了目标目录。这清理了缺少的设置工具,并使一切重新运行。

例如:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

I ran into this problem after updating my Ubuntu build. It seems to have gone through and removed set up tools in all of my virtual environments.

To remedy this I reinstalled the virtual environment back into the target directory. This cleaned up missing setup tools and got things running again.

e.g.:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

回答 25

对我来说,一个很好的解决方法是使用--no-download选项virtualenv(VIRTUALENV_NO_DOWNLOAD=1 tox用于tox。)

For me a good fix was to use --no-download option to virtualenv (VIRTUALENV_NO_DOWNLOAD=1 tox for tox.)


回答 26

在Opensuse 42.1上,以下内容解决了此问题:

zypper in python-Pygments

On Opensuse 42.1 the following fixed this issue:

zypper in python-Pygments

回答 27

ImportError:没有名为pkg_resources的模块:解决方法是使用下面的命令重新安装python pip。

步骤:1登录到root用户。

sudo su root

步骤:2卸载python-pip软件包(如果存在)。

apt-get purge -y python-pip

步骤:3使用wget命令下载文件(在中下载文件pwd

wget https://bootstrap.pypa.io/get-pip.py

步骤:4运行python文件。

python ./get-pip.py

步骤:5 Finalic exicute安装命令。

apt-get install python-pip

注意:用户必须是root用户。

ImportError: No module named pkg_resources: the solution is to reinstall python pip using the following Command are under.

Step: 1 Login in root user.

sudo su root

Step: 2 Uninstall python-pip package if existing.

apt-get purge -y python-pip

Step: 3 Download files using wget command(File download in pwd )

wget https://bootstrap.pypa.io/get-pip.py

Step: 4 Run python file.

python ./get-pip.py

Step: 5 Finaly exicute installation command.

apt-get install python-pip

Note: User must be root.


回答 28

我在Google App Engine环境中遇到了该错误。并pip install -t lib setuptools解决了问题。

I experienced that error in my Google App Engine environment. And pip install -t lib setuptools fixed the issue.


回答 29

如果您使用的是Python 3,则应使用pip3而不是pip。该命令看起来像$ pip3 install requirements.txt

If you are using Python 3, you should use pip3 instead of pip. The command looks like $ pip3 install requirements.txt


如何在Requirements.txt中声明直接的github源

问题:如何在Requirements.txt中声明直接的github源

我已经使用以下命令安装了一个库

pip install git+git://github.com/mozilla/elasticutils.git

直接从Github存储库安装它。这工作正常,我想在我的requirements.txt。我看其他的票像这样但这并没有解决我的问题。如果我把像

-f git+git://github.com/mozilla/elasticutils.git
elasticutils==0.7.dev

requirements.txt文件中,pip install -r requirements.txt结果为以下输出:

Downloading/unpacking elasticutils==0.7.dev (from -r requirements.txt (line 20))
  Could not find a version that satisfies the requirement elasticutils==0.7.dev (from -r requirements.txt (line 20)) (from versions: )
No distributions matching the version for elasticutils==0.7.dev (from -r requirements.txt (line 20))

需求文件文档中没有提及使用git+git协议说明符的链接,因此也许只是不被支持。

有人能解决我的问题吗?

I’ve installed a library using the command

pip install git+git://github.com/mozilla/elasticutils.git

which installs it directly from a Github repository. This works fine and I want to have that dependency in my requirements.txt. I’ve looked at other tickets like this but that didn’t solve my problem. If I put something like

-f git+git://github.com/mozilla/elasticutils.git
elasticutils==0.7.dev

in the requirements.txt file, a pip install -r requirements.txt results in the following output:

Downloading/unpacking elasticutils==0.7.dev (from -r requirements.txt (line 20))
  Could not find a version that satisfies the requirement elasticutils==0.7.dev (from -r requirements.txt (line 20)) (from versions: )
No distributions matching the version for elasticutils==0.7.dev (from -r requirements.txt (line 20))

The documentation of the requirements file does not mention links using the git+git protocol specifier, so maybe this is just not supported.

Does anybody have a solution for my problem?


回答 0

“ Editable”包语法可用于requirements.txt从各种VCS(git,hg,bzr,svn)导入包:

-e git://github.com/mozilla/elasticutils.git#egg=elasticutils

另外,可以指向特定的提交:

-e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils

“Editable” packages syntax can be used in requirements.txt to import packages from a variety of VCS (git, hg, bzr, svn):

-e git://github.com/mozilla/elasticutils.git#egg=elasticutils

Also, it is possible to point to particular commit:

-e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils

回答 1

通常,您的requirements.txt文件如下所示:

package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...

要指定Github存储库,您不需要package-name==约定。

下面的示例更新 package-two使用GitHub存储库进行。@和之间的文字#表示包装的详细信息。

指定提交哈希(41b95ec在updated的上下文中requirements.txt):

package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1

指定分支名称(master):

git+git://github.com/path/to/package-two@master#egg=package-two

指定标签(0.1):

git+git://github.com/path/to/package-two@0.1#egg=package-two

指定发布(3.7.1):

git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two

请注意,#egg=package-two此处不是注释,而是要明确说明软件包名称

这篇博客文章对此主题进行了更多讨论。

Normally your requirements.txt file would look something like this:

package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...

To specify a Github repo, you do not need the package-name== convention.

The examples below update package-two using a GitHub repo. The text between @ and # denotes the specifics of the package.

Specify commit hash (41b95ec in the context of updated requirements.txt):

package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1

Specify branch name (master):

git+git://github.com/path/to/package-two@master#egg=package-two

Specify tag (0.1):

git+git://github.com/path/to/package-two@0.1#egg=package-two

Specify release (3.7.1):

git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two

Note that #egg=package-two is not a comment here, it is to explicitly state the package name

This blog post has some more discussion on the topic.


回答 2

requirements.txt从pip 7.0开始,可以通过以下方式指定对git存储库中软件包的依赖关系:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e git+git@git.myproject.org:SomeProject#egg=SomeProject

对于Github,这意味着您可以做到(请注意,省略了-e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

为什么要额外回答?
-e在其他答案中对标志有些困惑,所以这是我的澄清:

-e或” --editable标志表示包装已安装在<venv path>/src/SomeProject深处,因此不会放入深处<venv path>/lib/pythonX.X/site-packages/SomeProject。否则,它将被放置在其中。2

文献资料

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e git+git@git.myproject.org:SomeProject#egg=SomeProject

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here’s my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation


回答 3

首先,以任何已知的方式使用git+git或安装git+https。安装项目kronok的分支的示例brabeion

pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion

其次,使用pip freeze > requirements.txt来获取正确的东西requirements.txt。在这种情况下,您将获得

-e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion-master

三,测试结果:

pip uninstall brabeion
pip install -r requirements.txt

First, install with git+git or git+https, in any way you know. Example of installing kronok‘s branch of the brabeion project:

pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion

Second, use pip freeze > requirements.txt to get the right thing in your requirements.txt. In this case, you will get

-e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion-master

Third, test the result:

pip uninstall brabeion
pip install -r requirements.txt

回答 4

由于pip v1.5(发布于2014年1月1日:CHANGELOGPR),您还可以指定git repo的子目录来包含您的模块。语法如下所示:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

注意:作为pip模块的作者,如果可能的话,理想情况下,您可能希望将模块发布到它自己的顶级仓库中。但是,此功能对于某些子目录中包含python模块的现有存储库很有帮助。如果它们也没有发布到pypi,则可能会被迫以这种方式安装它们。

Since pip v1.5, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

Note: As a pip module author, ideally you’d probably want to publish your module in it’s own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.


回答 5

我发现要获取pip3(v9.0.1,由Ubuntu 18.04的软件包管理器安装)来实际安装我告诉它要安装的东西有点棘手。我发布此答案是为了节省遇到此问题的任何人的时间。

将其放入Requirements.txt文件失败:

git+git://github.com/myname/myrepo.git@my-branch#egg=eggname

“失败”是指当它从Git下载代码时,它最终安装了PyPi上找到的代码的原始版本,而不是该分支上存储库中的代码。

但是,安装commmit而不是分支名称是可行的:

git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname

I’m finding that it’s kind of tricky to get pip3 (v9.0.1, as installed by Ubuntu 18.04’s package manager) to actually install the thing I tell it to install. I’m posting this answer to save anyone’s time who runs into this problem.

Putting this into a requirements.txt file failed:

git+git://github.com/myname/myrepo.git@my-branch#egg=eggname

By “failed” I mean that while it downloaded the code from Git, it ended up installing the original version of the code, as found on PyPi, instead of the code in the repo on that branch.

However, installing the commmit instead of the branch name works:

git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname

Python和pip,列出可用的软件包的所有版本?

问题:Python和pip,列出可用的软件包的所有版本?

给定可以与pip一起安装的Python软件包的名称,是否有任何方法可以找到pip可以安装的所有可能版本的列表?现在是反复试验。

我正在尝试为第三方库安装一个版本,但是最新版本太新了,进行了向后不兼容的更改。所以我想以某种方式列出pip知道的所有版本,以便我可以对其进行测试。

Given the name of a Python package that can be installed with pip, is there any way to find out a list of all the possible versions of it that pip could install? Right now it’s trial and error.

I’m trying to install a version for a third party library, but the newest version is too new, there were backwards incompatible changes made. So I’d like to somehow have a list of all the versions that pip knows about, so that I can test them.


回答 0

(更新:截至2020年3月,许多人报告说,通过安装的蛋黄pip install yolk3k只能返回最新版本。 克里斯的回答似乎最支持我,并为我工作)

pastebin上的脚本可以正常工作。但是,如果您要使用多个环境/主机,这不是很方便,因为您每次都必须复制/创建它。

更好的全方位解决方案是使用yolk3k,该软件可与pip一起安装。例如,查看可用的Django版本:

$ pip install yolk3k
$ yolk -V django
Django 1.3
Django 1.2.5
Django 1.2.4
Django 1.2.3
Django 1.2.2
Django 1.2.1
Django 1.2
Django 1.1.4
Django 1.1.3
Django 1.1.2
Django 1.0.4

yolk3k2012年yolk停止开发的原版的叉子。尽管已不再维护(如下面的注释所示),yolkyolk3k似乎并支持Python 3。

注意:我不参与yolk3k的开发。如果某些事情似乎无法正常工作,则在此处发表评论不会有太大的不同。请改用yolk3k问题追踪器,并考虑提交修订(如果可能)。

(update: As of March 2020, many people have reported that yolk, installed via pip install yolk3k, only returns latest version. Chris’s answer seems to have the most upvotes and worked for me)

The script at pastebin does work. However it’s not very convenient if you’re working with multiple environments/hosts because you will have to copy/create it every time.

A better all-around solution would be to use yolk3k, which is available to install with pip. E.g. to see what versions of Django are available:

$ pip install yolk3k
$ yolk -V django
Django 1.3
Django 1.2.5
Django 1.2.4
Django 1.2.3
Django 1.2.2
Django 1.2.1
Django 1.2
Django 1.1.4
Django 1.1.3
Django 1.1.2
Django 1.0.4

yolk3k is a fork of the original yolk which ceased development in 2012. Though yolk is no longer maintained (as indicated in comments below), yolk3k appears to be and supports Python 3.

Note: I am not involved in the development of yolk3k. If something doesn’t seem to work as it should, leaving a comment here should not make much difference. Use the yolk3k issue tracker instead and consider submitting a fix, if possible.


回答 1

用于PIP> = 9.0使用

$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from 
  versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

–将打印所有可用版本,而无需实际下载或安装任何其他软件包。

对于pip <9.0使用

pip install pylibmc==blork

在哪里blork可以是不是有效版本号的任何字符串。

For pip >= 9.0 use

$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from 
  versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

– all the available versions will be printed without actually downloading or installing any additional packages.

For pip < 9.0 use

pip install pylibmc==blork

where blork can be any string that is not a valid version number.


回答 2

更新:
自2017年9月起,此方法不再起作用:--no-install已在第7点中删除

采用 pip install -v,您可以查看所有可用的版本

root@node7:~# pip install web.py -v
Downloading/unpacking web.py
  Using version 0.37 (newest of versions: 0.37, 0.36, 0.35, 0.34, 0.33, 0.33, 0.32, 0.31, 0.22, 0.2)
  Downloading web.py-0.37.tar.gz (90Kb): 90Kb downloaded
  Running setup.py egg_info for package web.py
    running egg_info
    creating pip-egg-info/web.py.egg-info

要不安装任何软件包,请使用以下解决方案之一:

root@node7:~# pip install --no-deps --no-install flask -v                                                                                                      
Downloading/unpacking flask
  Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
  Downloading Flask-0.10.1.tar.gz (544Kb): 544Kb downloaded

要么

root@node7:~# cd $(mktemp -d)
root@node7:/tmp/tmp.c6H99cWD0g# pip install flask -d . -v
Downloading/unpacking flask
  Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
  Downloading Flask-0.10.1.tar.gz (544Kb): 4.1Kb downloaded

经过pip 1.0测试

root@node7:~# pip --version
pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7)

Update:
As of Sep 2017 this method no longer works: --no-install was removed in pip 7

Use pip install -v, you can see all versions that available

root@node7:~# pip install web.py -v
Downloading/unpacking web.py
  Using version 0.37 (newest of versions: 0.37, 0.36, 0.35, 0.34, 0.33, 0.33, 0.32, 0.31, 0.22, 0.2)
  Downloading web.py-0.37.tar.gz (90Kb): 90Kb downloaded
  Running setup.py egg_info for package web.py
    running egg_info
    creating pip-egg-info/web.py.egg-info

To not install any package, use one of following solution:

root@node7:~# pip install --no-deps --no-install flask -v                                                                                                      
Downloading/unpacking flask
  Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
  Downloading Flask-0.10.1.tar.gz (544Kb): 544Kb downloaded

or

root@node7:~# cd $(mktemp -d)
root@node7:/tmp/tmp.c6H99cWD0g# pip install flask -d . -v
Downloading/unpacking flask
  Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
  Downloading Flask-0.10.1.tar.gz (544Kb): 4.1Kb downloaded

Tested with pip 1.0

root@node7:~# pip --version
pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7)

回答 3

您不需要第三方软件包即可获取此信息。pypi为以下所有包提供了简单的JSON feed

https://pypi.python.org/pypi/{PKG_NAME}/json

以下是一些仅使用获取所有版本的标准库的Python代码。

import json
import urllib2
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib2.urlopen(urllib2.Request(url)))
    versions = data["releases"].keys()
    versions.sort(key=StrictVersion)
    return versions

print "\n".join(versions("scikit-image"))

该代码打印出来(截至2015年2月23日):

0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1

You don’t need a third party package to get this information. pypi provides simple JSON feeds for all packages under

https://pypi.python.org/pypi/{PKG_NAME}/json

Here’s some Python code using only the standard library which gets all versions.

import json
import urllib2
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib2.urlopen(urllib2.Request(url)))
    versions = data["releases"].keys()
    versions.sort(key=StrictVersion)
    return versions

print "\n".join(versions("scikit-image"))

That code prints (as of Feb 23rd, 2015):

0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1

回答 4

我想出了简单的bash脚本。感谢jq的作者。

#!/bin/bash
set -e

PACKAGE_JSON_URL="https://pypi.org/pypi/${1}/json"

curl -s "$PACKAGE_JSON_URL" | jq  -r '.releases | keys | .[]' | sort -V

更新:添加按版本号排序。

I came up with dead-simple bash script. Thanks to jq‘s author.

#!/bin/bash
set -e

PACKAGE_JSON_URL="https://pypi.org/pypi/${1}/json"

curl -s "$PACKAGE_JSON_URL" | jq  -r '.releases | keys | .[]' | sort -V

Update: Add sorting by version number.


回答 5

您可以使用yolk3k软件包而不是yolk。yolk3k是原始蛋黄的叉子,它同时支持python2和3。

https://github.com/myint/yolk

pip install yolk3k

You could the yolk3k package instead of yolk. yolk3k is a fork from the original yolk and it supports both python2 and 3.

https://github.com/myint/yolk

pip install yolk3k

回答 6

看了一段时间的pip代码后,看起来可以在中的PackageFinder类中找到负责定位软件包的代码pip.index。它的方法find_requirement查找的版本InstallRequirement,但不幸的是仅返回最新版本。

下面的代码几乎是原始函数的1:1副本,第114行的return更改为返回所有版本。

该脚本将一个包名称作为第一个也是唯一的参数,并返回所有版本。

http://pastebin.com/axzdUQhZ

我不保证正确性,因为我对pip的代码不熟悉。但希望这会有所帮助。

样品输出

python test.py pip
Versions of pip
0.8.2
0.8.1
0.8
0.7.2
0.7.1
0.7
0.6.3
0.6.2
0.6.1
0.6
0.5.1
0.5
0.4
0.3.1
0.3
0.2.1
0.2 dev

编码:

import posixpath
import pkg_resources
import sys
from pip.download import url_to_path
from pip.exceptions import DistributionNotFound
from pip.index import PackageFinder, Link
from pip.log import logger
from pip.req import InstallRequirement
from pip.util import Inf


class MyPackageFinder(PackageFinder):

    def find_requirement(self, req, upgrade):
        url_name = req.url_name
        # Only check main index if index URL is given:
        main_index_url = None
        if self.index_urls:
            # Check that we have the url_name correctly spelled:
            main_index_url = Link(posixpath.join(self.index_urls[0], url_name))
            # This will also cache the page, so it's okay that we get it again later:
            page = self._get_page(main_index_url, req)
            if page is None:
                url_name = self._find_url_name(Link(self.index_urls[0]), url_name, req) or req.url_name

        # Combine index URLs with mirror URLs here to allow
        # adding more index URLs from requirements files
        all_index_urls = self.index_urls + self.mirror_urls

        def mkurl_pypi_url(url):
            loc = posixpath.join(url, url_name)
            # For maximum compatibility with easy_install, ensure the path
            # ends in a trailing slash.  Although this isn't in the spec
            # (and PyPI can handle it without the slash) some other index
            # implementations might break if they relied on easy_install's behavior.
            if not loc.endswith('/'):
                loc = loc + '/'
            return loc
        if url_name is not None:
            locations = [
                mkurl_pypi_url(url)
                for url in all_index_urls] + self.find_links
        else:
            locations = list(self.find_links)
        locations.extend(self.dependency_links)
        for version in req.absolute_versions:
            if url_name is not None and main_index_url is not None:
                locations = [
                    posixpath.join(main_index_url.url, version)] + locations

        file_locations, url_locations = self._sort_locations(locations)

        locations = [Link(url) for url in url_locations]
        logger.debug('URLs to search for versions for %s:' % req)
        for location in locations:
            logger.debug('* %s' % location)
        found_versions = []
        found_versions.extend(
            self._package_versions(
                [Link(url, '-f') for url in self.find_links], req.name.lower()))
        page_versions = []
        for page in self._get_pages(locations, req):
            logger.debug('Analyzing links from page %s' % page.url)
            logger.indent += 2
            try:
                page_versions.extend(self._package_versions(page.links, req.name.lower()))
            finally:
                logger.indent -= 2
        dependency_versions = list(self._package_versions(
            [Link(url) for url in self.dependency_links], req.name.lower()))
        if dependency_versions:
            logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
        file_versions = list(self._package_versions(
                [Link(url) for url in file_locations], req.name.lower()))
        if not found_versions and not page_versions and not dependency_versions and not file_versions:
            logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
            raise DistributionNotFound('No distributions at all found for %s' % req)
        if req.satisfied_by is not None:
            found_versions.append((req.satisfied_by.parsed_version, Inf, req.satisfied_by.version))
        if file_versions:
            file_versions.sort(reverse=True)
            logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions]))
            found_versions = file_versions + found_versions
        all_versions = found_versions + page_versions + dependency_versions
        applicable_versions = []
        for (parsed_version, link, version) in all_versions:
            if version not in req.req:
                logger.info("Ignoring link %s, version %s doesn't match %s"
                            % (link, version, ','.join([''.join(s) for s in req.req.specs])))
                continue
            applicable_versions.append((link, version))
        applicable_versions = sorted(applicable_versions, key=lambda v: pkg_resources.parse_version(v[1]), reverse=True)
        existing_applicable = bool([link for link, version in applicable_versions if link is Inf])
        if not upgrade and existing_applicable:
            if applicable_versions[0][1] is Inf:
                logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
                            % req.satisfied_by.version)
            else:
                logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
                            % (req.satisfied_by.version, applicable_versions[0][1]))
            return None
        if not applicable_versions:
            logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
                         % (req, ', '.join([version for parsed_version, link, version in found_versions])))
            raise DistributionNotFound('No distributions matching the version for %s' % req)
        if applicable_versions[0][0] is Inf:
            # We have an existing version, and its the best version
            logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
                        % (req.satisfied_by.version, ', '.join([version for link, version in applicable_versions[1:]]) or 'none'))
            return None
        if len(applicable_versions) > 1:
            logger.info('Using version %s (newest of versions: %s)' %
                        (applicable_versions[0][1], ', '.join([version for link, version in applicable_versions])))
        return applicable_versions


if __name__ == '__main__':
    req = InstallRequirement.from_line(sys.argv[1], None)
    finder = MyPackageFinder([], ['http://pypi.python.org/simple/'])
    versions = finder.find_requirement(req, False)
    print 'Versions of %s' % sys.argv[1]
    for v in versions:
        print v[1]

After looking at pip’s code for a while, it looks like the code responsible for locating packages can be found in the PackageFinder class in pip.index. Its method find_requirement looks up the versions of a InstallRequirement, but unfortunately only returns the most recent version.

The code below is almost a 1:1 copy of the original function, with the return in line 114 changed to return all versions.

The script expects one package name as first and only argument and returns all versions.

http://pastebin.com/axzdUQhZ

I can’t guarantee for the correctness, as I’m not familiar with pip’s code. But hopefully this helps.

Sample output

python test.py pip
Versions of pip
0.8.2
0.8.1
0.8
0.7.2
0.7.1
0.7
0.6.3
0.6.2
0.6.1
0.6
0.5.1
0.5
0.4
0.3.1
0.3
0.2.1
0.2 dev

The code:

import posixpath
import pkg_resources
import sys
from pip.download import url_to_path
from pip.exceptions import DistributionNotFound
from pip.index import PackageFinder, Link
from pip.log import logger
from pip.req import InstallRequirement
from pip.util import Inf


class MyPackageFinder(PackageFinder):

    def find_requirement(self, req, upgrade):
        url_name = req.url_name
        # Only check main index if index URL is given:
        main_index_url = None
        if self.index_urls:
            # Check that we have the url_name correctly spelled:
            main_index_url = Link(posixpath.join(self.index_urls[0], url_name))
            # This will also cache the page, so it's okay that we get it again later:
            page = self._get_page(main_index_url, req)
            if page is None:
                url_name = self._find_url_name(Link(self.index_urls[0]), url_name, req) or req.url_name

        # Combine index URLs with mirror URLs here to allow
        # adding more index URLs from requirements files
        all_index_urls = self.index_urls + self.mirror_urls

        def mkurl_pypi_url(url):
            loc = posixpath.join(url, url_name)
            # For maximum compatibility with easy_install, ensure the path
            # ends in a trailing slash.  Although this isn't in the spec
            # (and PyPI can handle it without the slash) some other index
            # implementations might break if they relied on easy_install's behavior.
            if not loc.endswith('/'):
                loc = loc + '/'
            return loc
        if url_name is not None:
            locations = [
                mkurl_pypi_url(url)
                for url in all_index_urls] + self.find_links
        else:
            locations = list(self.find_links)
        locations.extend(self.dependency_links)
        for version in req.absolute_versions:
            if url_name is not None and main_index_url is not None:
                locations = [
                    posixpath.join(main_index_url.url, version)] + locations

        file_locations, url_locations = self._sort_locations(locations)

        locations = [Link(url) for url in url_locations]
        logger.debug('URLs to search for versions for %s:' % req)
        for location in locations:
            logger.debug('* %s' % location)
        found_versions = []
        found_versions.extend(
            self._package_versions(
                [Link(url, '-f') for url in self.find_links], req.name.lower()))
        page_versions = []
        for page in self._get_pages(locations, req):
            logger.debug('Analyzing links from page %s' % page.url)
            logger.indent += 2
            try:
                page_versions.extend(self._package_versions(page.links, req.name.lower()))
            finally:
                logger.indent -= 2
        dependency_versions = list(self._package_versions(
            [Link(url) for url in self.dependency_links], req.name.lower()))
        if dependency_versions:
            logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
        file_versions = list(self._package_versions(
                [Link(url) for url in file_locations], req.name.lower()))
        if not found_versions and not page_versions and not dependency_versions and not file_versions:
            logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
            raise DistributionNotFound('No distributions at all found for %s' % req)
        if req.satisfied_by is not None:
            found_versions.append((req.satisfied_by.parsed_version, Inf, req.satisfied_by.version))
        if file_versions:
            file_versions.sort(reverse=True)
            logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions]))
            found_versions = file_versions + found_versions
        all_versions = found_versions + page_versions + dependency_versions
        applicable_versions = []
        for (parsed_version, link, version) in all_versions:
            if version not in req.req:
                logger.info("Ignoring link %s, version %s doesn't match %s"
                            % (link, version, ','.join([''.join(s) for s in req.req.specs])))
                continue
            applicable_versions.append((link, version))
        applicable_versions = sorted(applicable_versions, key=lambda v: pkg_resources.parse_version(v[1]), reverse=True)
        existing_applicable = bool([link for link, version in applicable_versions if link is Inf])
        if not upgrade and existing_applicable:
            if applicable_versions[0][1] is Inf:
                logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
                            % req.satisfied_by.version)
            else:
                logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
                            % (req.satisfied_by.version, applicable_versions[0][1]))
            return None
        if not applicable_versions:
            logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
                         % (req, ', '.join([version for parsed_version, link, version in found_versions])))
            raise DistributionNotFound('No distributions matching the version for %s' % req)
        if applicable_versions[0][0] is Inf:
            # We have an existing version, and its the best version
            logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
                        % (req.satisfied_by.version, ', '.join([version for link, version in applicable_versions[1:]]) or 'none'))
            return None
        if len(applicable_versions) > 1:
            logger.info('Using version %s (newest of versions: %s)' %
                        (applicable_versions[0][1], ', '.join([version for link, version in applicable_versions])))
        return applicable_versions


if __name__ == '__main__':
    req = InstallRequirement.from_line(sys.argv[1], None)
    finder = MyPackageFinder([], ['http://pypi.python.org/simple/'])
    versions = finder.find_requirement(req, False)
    print 'Versions of %s' % sys.argv[1]
    for v in versions:
        print v[1]

回答 7

您可以使用这个小的Python 3脚本(仅使用标准库模块)来使用JSON API从PyPI抓取软件包的可用版本列表,并以相反的时间顺序打印它们。不像其他一些Python的解决方案张贴在这里,但这并不松散的版本一样突破django2.2rc1还是uwsgi2.0.17.1

#!/usr/bin/env python3

import json
import sys
from urllib import request    
from pkg_resources import parse_version    

def versions(pkg_name):
    url = f'https://pypi.python.org/pypi/{pkg_name}/json'
    releases = json.loads(request.urlopen(url).read())['releases']
    return sorted(releases, key=parse_version, reverse=True)    

if __name__ == '__main__':
    print(*versions(sys.argv[1]), sep='\n')

保存脚本并以包名称作为参数运行它,例如:

python versions.py django
3.0a1
2.2.5
2.2.4
2.2.3
2.2.2
2.2.1
2.2
2.2rc1
...

You can use this small Python 3 script (using only standard library modules) to grab the list of available versions for a package from PyPI using JSON API and print them in reverse chronological order. Unlike some other Python solutions posted here, this doesn’t break on loose versions like django‘s 2.2rc1 or uwsgi‘s 2.0.17.1:

#!/usr/bin/env python3

import json
import sys
from urllib import request    
from pkg_resources import parse_version    

def versions(pkg_name):
    url = f'https://pypi.python.org/pypi/{pkg_name}/json'
    releases = json.loads(request.urlopen(url).read())['releases']
    return sorted(releases, key=parse_version, reverse=True)    

if __name__ == '__main__':
    print(*versions(sys.argv[1]), sep='\n')

Save the script and run it with the package name as an argument, e.g.:

python versions.py django
3.0a1
2.2.5
2.2.4
2.2.3
2.2.2
2.2.1
2.2
2.2rc1
...

回答 8

https://pypi.python.org/pypi/Django/适用于维护者选择显示所有软件包的软件包 https://pypi.python.org/simple/pip/-无论如何都应该做到这一点(列出所有链接)

https://pypi.python.org/pypi/Django/ – works for packages whose maintainers choose to show all packages https://pypi.python.org/simple/pip/ – should do the trick anyhow (lists all links)


回答 9

这对我在OSX上有效:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n'

它每行返回一个列表:

1.1.0rc1
1.1.0rc2
1.1.0
1.2.0rc1
1.2.0rc2
1.2.0rc3
1.2.0rc4
1.2.0
1.3.0rc1
1.3.0rc2
1.3.0rc3
1.3.0
1.3.1
1.3.2
1.3.3
1.4.0rc1
1.4.0rc2
1.4.0rc3
1.4.0
1.4.1
1.4.2
1.5.0rc1
1.5.0rc2
1.5.0rc3
1.5.0
1.5.1
1.5.2
1.6.0rc1
1.6.0
1.6.1
1.6.2
1.7.0rc1
1.7.0rc2
1.7.0
1.7.1
1.8.0rc1
1.8.0rc2
1.8.0
1.8.1
1.9.0rc1
1.9.0rc2
1.9.0rc3
1.9.0rc4
1.9.0
1.10.0rc1
1.10.0rc2
1.10.0

或获取可用的最新版本:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n' \
| gsort -r -V \
| head -1
1.10.0rc2

请记住gsort,必须安装(在OSX上)以解析版本。您可以使用安装brew install coreutils

This works for me on OSX:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n'

It returns the list one per line:

1.1.0rc1
1.1.0rc2
1.1.0
1.2.0rc1
1.2.0rc2
1.2.0rc3
1.2.0rc4
1.2.0
1.3.0rc1
1.3.0rc2
1.3.0rc3
1.3.0
1.3.1
1.3.2
1.3.3
1.4.0rc1
1.4.0rc2
1.4.0rc3
1.4.0
1.4.1
1.4.2
1.5.0rc1
1.5.0rc2
1.5.0rc3
1.5.0
1.5.1
1.5.2
1.6.0rc1
1.6.0
1.6.1
1.6.2
1.7.0rc1
1.7.0rc2
1.7.0
1.7.1
1.8.0rc1
1.8.0rc2
1.8.0
1.8.1
1.9.0rc1
1.9.0rc2
1.9.0rc3
1.9.0rc4
1.9.0
1.10.0rc1
1.10.0rc2
1.10.0

Or to get the latest version available:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n' \
| gsort -r -V \
| head -1
1.10.0rc2

Keep in mind gsort has to be installed (on OSX) to parse the versions. You can install it with brew install coreutils


回答 10

我的项目luddite具有此功能。

用法示例:

>>> import luddite
>>> luddite.get_versions_pypi("python-dateutil")
('0.1', '0.3', '0.4', '0.5', '1.0', '1.1', '1.2', '1.4', '1.4.1', '1.5', '2.0', '2.1', '2.2', '2.3', '2.4.0', '2.4.1', '2.4.2', '2.5.0', '2.5.1', '2.5.2', '2.5.3', '2.6.0', '2.6.1', '2.7.0', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.8.0')

通过查询https://pypi.org/的json API,它列出了可用软件包的所有版本。

My project luddite has this feature.

Example usage:

>>> import luddite
>>> luddite.get_versions_pypi("python-dateutil")
('0.1', '0.3', '0.4', '0.5', '1.0', '1.1', '1.2', '1.4', '1.4.1', '1.5', '2.0', '2.1', '2.2', '2.3', '2.4.0', '2.4.1', '2.4.2', '2.5.0', '2.5.1', '2.5.2', '2.5.3', '2.6.0', '2.6.1', '2.7.0', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.8.0')

It lists all versions of a package available, by querying the json API of https://pypi.org/


回答 11

我没有任何运气yolkyolk3kpip install -v可是所以最后我用这个(埃里克蒋介石的回答适合到Python 3):

import json
import requests
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/{}/json".format(package_name)
    data = requests.get(url).json()
    return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)

>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...

I didn’t have any luck with yolk, yolk3k or pip install -v but so I ended up using this (adapted to Python 3 from eric chiang’s answer):

import json
import requests
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/{}/json".format(package_name)
    data = requests.get(url).json()
    return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)

>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...

回答 12

另一种解决方案是使用Warehouse API:

https://warehouse.readthedocs.io/api-reference/json/#release

例如Flask:

import requests
r = requests.get("https://pypi.org/pypi/Flask/json")
print(r.json()['releases'].keys())

将打印:

dict_keys(['0.1', '0.10', '0.10.1', '0.11', '0.11.1', '0.12', '0.12.1', '0.12.2', '0.12.3', '0.12.4', '0.2', '0.3', '0.3.1', '0.4', '0.5', '0.5.1', '0.5.2', '0.6', '0.6.1', '0.7', '0.7.1', '0.7.2', '0.8', '0.8.1', '0.9', '1.0', '1.0.1', '1.0.2'])

Alternative solution is to use the Warehouse APIs:

https://warehouse.readthedocs.io/api-reference/json/#release

For instance for Flask:

import requests
r = requests.get("https://pypi.org/pypi/Flask/json")
print(r.json()['releases'].keys())

will print:

dict_keys(['0.1', '0.10', '0.10.1', '0.11', '0.11.1', '0.12', '0.12.1', '0.12.2', '0.12.3', '0.12.4', '0.2', '0.3', '0.3.1', '0.4', '0.5', '0.5.1', '0.5.2', '0.6', '0.6.1', '0.7', '0.7.1', '0.7.2', '0.8', '0.8.1', '0.9', '1.0', '1.0.1', '1.0.2'])

回答 13

bash仅依赖于python自身的简单脚本(我假设应该在问题的上下文中进行安装)以及curl或之一wget。假设您已setuptools安装软件包以对版本进行排序(几乎始终已安装)。它不依赖外部依赖项,例如:

  • jq 可能不存在;
  • grep并且awk在Linux和macOS上的行为可能有所不同。
curl --silent --location https://pypi.org/pypi/requests/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))"

带有注释的较长版本。

将包名称放入变量中:

PACKAGE=requests

获取版本(使用curl):

VERSIONS=$(curl --silent --location https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

获取版本(使用wget):

VERSIONS=$(wget -qO- https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

打印排序版本:

echo $VERSIONS

Simple bash script that relies only on python itself (I assume that in the context of the question it should be installed) and one of curl or wget. It has an assumption that you have setuptools package installed to sort versions (almost always installed). It doesn’t rely on external dependencies such as:

  • jq which may not be present;
  • grep and awk that may behave differently on Linux and macOS.
curl --silent --location https://pypi.org/pypi/requests/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))"

A little bit longer version with comments.

Put the package name into a variable:

PACKAGE=requests

Get versions (using curl):

VERSIONS=$(curl --silent --location https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

Get versions (using wget):

VERSIONS=$(wget -qO- https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

Print sorted versions:

echo $VERSIONS

回答 14

我的看法是结合了几个已发布的答案,并进行了一些修改,以使其在运行中的python环境中更易于使用。

这个想法是提供一个全新的命令(在install命令之后建模),为您提供要使用的软件包查找程序的实例。好处是,它可以与pip支持并读取本地pip配置文件的任何索引一起使用并使用,因此您可以获得与普通pip安装相同的正确结果。

我已经尝试使其与pip v 9.x和10.x兼容。.但是仅在9.x上尝试过

https://gist.github.com/kaos/68511bd013fcdebe766c981f50b473d4

#!/usr/bin/env python
# When you want a easy way to get at all (or the latest) version of a certain python package from a PyPi index.

import sys
import logging

try:
    from pip._internal import cmdoptions, main
    from pip._internal.commands import commands_dict
    from pip._internal.basecommand import RequirementCommand
except ImportError:
    from pip import cmdoptions, main
    from pip.commands import commands_dict
    from pip.basecommand import RequirementCommand

from pip._vendor.packaging.version import parse as parse_version

logger = logging.getLogger('pip')

class ListPkgVersionsCommand(RequirementCommand):
    """
    List all available versions for a given package from:

    - PyPI (and other indexes) using requirement specifiers.
    - VCS project urls.
    - Local project directories.
    - Local or remote source archives.

    """
    name = "list-pkg-versions"
    usage = """
      %prog [options] <requirement specifier> [package-index-options] ...
      %prog [options] [-e] <vcs project url> ...
      %prog [options] [-e] <local project path> ...
      %prog [options] <archive url/path> ..."""

    summary = 'List package versions.'

    def __init__(self, *args, **kw):
        super(ListPkgVersionsCommand, self).__init__(*args, **kw)

        cmd_opts = self.cmd_opts

        cmd_opts.add_option(cmdoptions.install_options())
        cmd_opts.add_option(cmdoptions.global_options())
        cmd_opts.add_option(cmdoptions.use_wheel())
        cmd_opts.add_option(cmdoptions.no_use_wheel())
        cmd_opts.add_option(cmdoptions.no_binary())
        cmd_opts.add_option(cmdoptions.only_binary())
        cmd_opts.add_option(cmdoptions.pre())
        cmd_opts.add_option(cmdoptions.require_hashes())

        index_opts = cmdoptions.make_option_group(
            cmdoptions.index_group,
            self.parser,
        )

        self.parser.insert_option_group(0, index_opts)
        self.parser.insert_option_group(0, cmd_opts)

    def run(self, options, args):
        cmdoptions.resolve_wheel_no_use_binary(options)
        cmdoptions.check_install_build_global(options)

        with self._build_session(options) as session:
            finder = self._build_package_finder(options, session)

            # do what you please with the finder object here... ;)
            for pkg in args:
                logger.info(
                    '%s: %s', pkg,
                    ', '.join(
                        sorted(
                            set(str(c.version) for c in finder.find_all_candidates(pkg)),
                            key=parse_version,
                        )
                    )
                )


commands_dict[ListPkgVersionsCommand.name] = ListPkgVersionsCommand

if __name__ == '__main__':
    sys.exit(main())

输出示例

./list-pkg-versions.py list-pkg-versions pika django
pika: 0.5, 0.5.1, 0.5.2, 0.9.1a0, 0.9.2a0, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 0.9.10, 0.9.11, 0.9.12, 0.9.13, 0.9.14, 0.10.0b1, 0.10.0b2, 0.10.0, 0.11.0b1, 0.11.0, 0.11.1, 0.11.2, 0.12.0b2
django: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4

My take is a combination of a couple of posted answers, with some modifications to make them easier to use from within a running python environment.

The idea is to provide a entirely new command (modeled after the install command) that gives you an instance of the package finder to use. The upside is that it works with, and uses, any indexes that pip supports and reads your local pip configuration files, so you get the correct results as you would with a normal pip install.

I’ve made an attempt at making it compatible with both pip v 9.x and 10.x.. but only tried it on 9.x

https://gist.github.com/kaos/68511bd013fcdebe766c981f50b473d4

#!/usr/bin/env python
# When you want a easy way to get at all (or the latest) version of a certain python package from a PyPi index.

import sys
import logging

try:
    from pip._internal import cmdoptions, main
    from pip._internal.commands import commands_dict
    from pip._internal.basecommand import RequirementCommand
except ImportError:
    from pip import cmdoptions, main
    from pip.commands import commands_dict
    from pip.basecommand import RequirementCommand

from pip._vendor.packaging.version import parse as parse_version

logger = logging.getLogger('pip')

class ListPkgVersionsCommand(RequirementCommand):
    """
    List all available versions for a given package from:

    - PyPI (and other indexes) using requirement specifiers.
    - VCS project urls.
    - Local project directories.
    - Local or remote source archives.

    """
    name = "list-pkg-versions"
    usage = """
      %prog [options] <requirement specifier> [package-index-options] ...
      %prog [options] [-e] <vcs project url> ...
      %prog [options] [-e] <local project path> ...
      %prog [options] <archive url/path> ..."""

    summary = 'List package versions.'

    def __init__(self, *args, **kw):
        super(ListPkgVersionsCommand, self).__init__(*args, **kw)

        cmd_opts = self.cmd_opts

        cmd_opts.add_option(cmdoptions.install_options())
        cmd_opts.add_option(cmdoptions.global_options())
        cmd_opts.add_option(cmdoptions.use_wheel())
        cmd_opts.add_option(cmdoptions.no_use_wheel())
        cmd_opts.add_option(cmdoptions.no_binary())
        cmd_opts.add_option(cmdoptions.only_binary())
        cmd_opts.add_option(cmdoptions.pre())
        cmd_opts.add_option(cmdoptions.require_hashes())

        index_opts = cmdoptions.make_option_group(
            cmdoptions.index_group,
            self.parser,
        )

        self.parser.insert_option_group(0, index_opts)
        self.parser.insert_option_group(0, cmd_opts)

    def run(self, options, args):
        cmdoptions.resolve_wheel_no_use_binary(options)
        cmdoptions.check_install_build_global(options)

        with self._build_session(options) as session:
            finder = self._build_package_finder(options, session)

            # do what you please with the finder object here... ;)
            for pkg in args:
                logger.info(
                    '%s: %s', pkg,
                    ', '.join(
                        sorted(
                            set(str(c.version) for c in finder.find_all_candidates(pkg)),
                            key=parse_version,
                        )
                    )
                )


commands_dict[ListPkgVersionsCommand.name] = ListPkgVersionsCommand

if __name__ == '__main__':
    sys.exit(main())

Example output

./list-pkg-versions.py list-pkg-versions pika django
pika: 0.5, 0.5.1, 0.5.2, 0.9.1a0, 0.9.2a0, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 0.9.10, 0.9.11, 0.9.12, 0.9.13, 0.9.14, 0.10.0b1, 0.10.0b2, 0.10.0, 0.11.0b1, 0.11.0, 0.11.1, 0.11.2, 0.12.0b2
django: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4

删除点子的缓存?

问题:删除点子的缓存?

我需要专门安装psycopg2 v2.4.1。我不小心做了:

 pip install psycopg2

代替:

 pip install psycopg2==2.4.1

它将安装2.4.4,而不是早期版本。

现在,即使在我pip卸载psycopg2并尝试使用正确的版本重新安装后,pip似乎仍在重新使用它第一次下载的缓存。

如何强制pip清除其下载缓存并使用命令中包含的特定版本?

I need to install psycopg2 v2.4.1 specifically. I accidentally did:

 pip install psycopg2

Instead of:

 pip install psycopg2==2.4.1

That installs 2.4.4 instead of the earlier version.

Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re-using the cache it downloaded the first time.

How can I force pip to clear out its download cache and use the specific version I’m including in the command?


回答 0

如果使用的是pip 6.0或更高版本,请尝试添加该--no-cache-dir选项

如果使用的是pip 6.0之前的版本,请使用进行升级pip install -U pip

If using pip 6.0 or newer, try adding the --no-cache-dir option.

If using pip older than pip 6.0, upgrade it with pip install -U pip.


回答 1

在适合您的系统的地方清除缓存目录

Linux和Unix

~/.cache/pip  # and it respects the XDG_CACHE_HOME directory.

OS X

~/Library/Caches/pip

视窗

%LocalAppData%\pip\Cache

Clear the cache directory where appropriate for your system

Linux and Unix

~/.cache/pip  # and it respects the XDG_CACHE_HOME directory.

OS X

~/Library/Caches/pip

Windows

%LocalAppData%\pip\Cache

回答 2

https://pip.pypa.io/zh-CN/latest/reference/pip_install.html#caching的文档中:

从v6.0开始,pip提供了默认情况下的缓存,其功能类似于网络浏览器。默认情况下,当缓存处于打开状态并且被设计为默认时,您可以禁用缓存并始终通过使用该--no-cache-dir 选项来访问PyPI 。

From documentation at https://pip.pypa.io/en/latest/reference/pip_install.html#caching:

Starting with v6.0, pip provides an on-by-default cache which functions similarly to that of a web browser. While the cache is on by default and is designed do the right thing by default you can disable the cache and always access PyPI by utilizing the --no-cache-dir option.


回答 3

pip可以安装一个忽略缓存的软件包,像这样

pip --no-cache-dir install scipy

pip can install a package ignoring the cache, like this

pip --no-cache-dir install scipy

回答 4

在Ubuntu上,我必须删除/tmp/pip-build-root

On Ubuntu, I had to delete /tmp/pip-build-root.


回答 5

(这里是点子维护者!)

由于PIP 6.0(后在2014年!) pip installpip download并且pip wheel命令可以告诉避免使用与高速缓存--no-cache-dir选项。(例如:pip install --no-cache-dir <package>

自pip 10.0(早在2018年!)以来,pip config添加了一个命令,该命令可用于将pip配置为始终忽略缓存- pip config set global.cache-dir false将pip配置为不“全局”使用缓存(即,在所有命令中)。

从pip 20.1开始,pip具有pip cache管理pip缓存内容的命令。

  • pip cache purge 删除缓存中的所有wheel文件。
  • pip cache remove matplotlib 有选择地从缓存中删除与matplotlib相关的文件。

总而言之,pip提供了许多调整缓存使用方式的方法:

  • pip install --no-cache-dir <package>:仅为此运行而无需使用缓存安装软件包。
  • pip config set global.cache-dir false:将pip配置为不“全局”使用缓存(在所有命令中)
  • pip cache remove matplotlib:从pip的缓存中删除所有与matplotlib相关的wheel文件。
  • pip cache purge:清除pip缓存中的所有文件。

问题中提到的“由于缓存而安装了错误版本”的特定问题已在pip 1.4中修复(早在2013年!):

修复了许多与清理和不重用构建目录有关的问题。(#413,#709,#634,#602,#939,#865,#948)

(pip maintainer here!)

Since pip 6.0 (back in 2014!), pip install, pip download and pip wheel commands can be told to avoid using the cache with the --no-cache-dir option. (eg: pip install --no-cache-dir <package>)

Since pip 10.0 (back in 2018!), a pip config command was added, which can be used to configure pip to always ignore the cache — pip config set global.cache-dir false configures pip to not use the cache “globally” (i.e. in all commands).

Since pip 20.1, pip has a pip cache command to manage the contents of pip’s cache.

  • pip cache purge removes all the wheel files in the cache.
  • pip cache remove matplotlib selectively removes files related to a matplotlib from the cache.

In summary, pip provides a lot of ways to tweak how it uses the cache:

  • pip install --no-cache-dir <package>: install a package without using the cache, for just this run.
  • pip config set global.cache-dir false: configure pip to not use the cache “globally” (in all commands)
  • pip cache remove matplotlib: removes all wheel files related to matplotlib from pip’s cache.
  • pip cache purge: to clear all files from pip’s cache.

The specific issue of “installing the wrong version due to caching” issue mentioned in the question was fixed in pip 1.4 (back in 2013!):

Fix a number of issues related to cleaning up and not reusing build directories. (#413, #709, #634, #602, #939, #865, #948)


回答 6

如果您想--no-cache-dir默认设置选项,可以将其放入pip.conf

[global]
no-cache-dir = false

的位置pip.conf取决于您的操作系统。请参阅文档以获取更多信息。

If you like to set the --no-cache-dir option by default, you can put this into pip.conf:

[global]
no-cache-dir = false

The location of pip.conf depends on your OS. See the documentation for more info.


回答 7

我只是遇到了类似的问题,发现获取pip升级软件包的唯一方法是删除以前未完成的安装或先前版本的pip可能遗留下的$PWD/build%CD%\build在Windows上)目录(它现在删除了成功安装后生成目录)。

I just had a similar problem and found that the only way to get pip to upgrade the package was to delete the $PWD/build (%CD%\build on Windows) directory that might have been left over from a previously unfinished install or a previous version of pip (it now deletes the build directories after a successful install).


回答 8

在archlinux中,pip缓存位于〜/ .cache / pip上,我可以通过删除其中的http文件夹来解决问题。

On archlinux pip cache is located at ~/.cache/pip, I could solve my issue by removing the http folder inside it.


回答 9

在我的Mac上,我必须删除缓存目录 ~/Library/Caches/pip/

On my mac I had to remove the cache directory ~/Library/Caches/pip/


回答 10

2020年4月21日发布pip 20.1b1以来,它“添加pip cache了检查/管理pip的转盘缓存的命令”,因此可以发出以下命令:

pip cache purge

参考指南在这里:
https : //pip.pypa.io/en/stable/reference/pip_cache/
相应的拉取请求在这里

Since pip 20.1b1, which was released on 21 April 2020 and “added pip cache command for inspecting/managing pip’s wheel cache”, it is possible to issue this command:

pip cache purge

The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.


回答 11

在Windows 7上,我必须删除%HOMEPATH%/pip

On Windows 7, I had to delete %HOMEPATH%/pip.


回答 12

如果使用virtualenv,请build在您的环境根目录下查找目录。

If using virtualenv, look for the build directory under your environments root.


回答 13

我必须在Windows 7上删除%TEMP%\ pip-build

I had to delete %TEMP%\pip-build On Windows 7


回答 14

在Mac OS(小牛)上,我不得不删除 /tmp/pip-build/

On Mac OS (Mavericks), I had to delete /tmp/pip-build/


回答 15

更好的方法是删除缓存并重建它。这样,如果您再次为其他virtualenv安装它,它将使用缓存而不是每次安装时都进行构建。

例如,当您安装它时,它将说它使用了缓存的滚轮,

Processing <some_prefix>/Library/Caches/pip/wheels/d0/c4/e4/e49fd07bca8dda00dd6b4bbc606aa05a25aacb00d45747a47a/horovod-0.19.3-cp37-cp37m-macosx_10_9_x86_64.wh

只需删除该文件,然后重新开始安装即可。

A better way to do it is to delete the cache and rebuild it. In this way, if you install it again for other virtualenv, it will use the cache instead of building every time when you install it.

For example, when you install it, it will say it uses cached wheel,

Processing <some_prefix>/Library/Caches/pip/wheels/d0/c4/e4/e49fd07bca8dda00dd6b4bbc606aa05a25aacb00d45747a47a/horovod-0.19.3-cp37-cp37m-macosx_10_9_x86_64.wh

Just delete that one and restart your install.


回答 16

(…)似乎pip正在重新使用缓存(…)

我很确定这不是正在发生的事情。用来(错误地)重用构建目录而非缓存的Pip。此问题已在 2013年7月23日发布的pip版本1.4中修复

(…) it appears that pip is re-using the cache (…)

I’m pretty sure that’s not what’s happening. Pip used to (wrongly) reuse build directory not cache. This was fixed in version 1.4 of pip which was released on 2013-07-23.


使用pip将Python软件包安装到其他目​​录中吗?

问题:使用pip将Python软件包安装到其他目​​录中吗?

我知道明显的答案是使用virtualenv和virtualenvwrapper,但是由于种种原因,我不能/不想这样做。

那么我该如何修改命令

pip install package_name

使pip软件包安装在默认位置以外的地方site-packages

I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can’t/don’t want to do that.

So how do I modify the command

pip install package_name

to make pip install the package somewhere other than the default site-packages?


回答 0

采用:

pip install --install-option="--prefix=$PREFIX_PATH" package_name

您可能还想--ignore-installed使用此新前缀来强制重新安装所有依赖项。您可以--install-option多次使用以添加可以使用的任何选项python setup.py install--prefix可能是您想要的,但是可以使用很多其他选项)。

Use:

pip install --install-option="--prefix=$PREFIX_PATH" package_name

You might also want to use --ignore-installed to force all dependencies to be reinstalled using this new prefix. You can use --install-option to multiple times to add any of the options you can use with python setup.py install (--prefix is probably what you want, but there are a bunch more options you could use).


回答 1

–target开关是你正在寻找的东西:

pip install --target=d:\somewhere\other\than\the\default package_name

但是您仍然需要添加d:\somewhere\other\than\the\defaultPYTHONPATH该位置才能实际使用它们。

-t,–target <dir>
将软件包安装到<dir>中。默认情况下,这不会替换<dir>中的现有文件/文件夹。
使用–upgrade将<dir>中的现有软件包替换为新版本。


如果目标开关不可用,请升级点子:

在Linux或OS X上:

pip install -U pip

在Windows上(这可以解决问题):

python -m pip install -U pip

The –target switch is the thing you’re looking for:

pip install --target=d:\somewhere\other\than\the\default package_name

But you still need to add d:\somewhere\other\than\the\default to PYTHONPATH to actually use them from that location.

-t, –target <dir>
Install packages into <dir>. By default this will not replace existing files/folders in <dir>.
Use –upgrade to replace existing packages in <dir> with new versions.


Upgrade pip if target switch is not available:

On Linux or OS X:

pip install -U pip

On Windows (this works around an issue):

python -m pip install -U pip

回答 2

代替--target选项或--install-options选项,我发现以下方法很好用(来自有关此问题的错误讨论,网址https://github.com/pypa/pip/issues/446):

PYTHONUSERBASE=/path/to/install/to pip install --user

(或者PYTHONUSERBASE在运行命令之前使用,在您的环境中设置目录export PYTHONUSERBASE=/path/to/install/to

它使用了非常有用的--user选项,但告诉它使binlibshare你会在一个自定义的前缀期待,而不是和其他目录$HOME/.local

然后,你可以到你添加这个PATHPYTHONPATH你将一个正常的安装目录和其他变量。

请注意,如果依赖于此的任何软件包都需要在目录中安装较新的版本,则您可能还需要指定--upgrade--ignore-installed选项PYTHONUSERBASE,以覆盖系统提供的版本。

一个完整的例子:

PYTHONUSERBASE=/opt/mysterypackage-1.0/python-deps pip install --user --upgrade numpy scipy

..将最新版本的scipy并将numpy最新版本安装并打包到一个目录中,然后可以将其包含在目录中PYTHONPATH(对于本示例,在CentOS 6上使用bash和python 2.6):

export PYTHONPATH=/opt/mysterypackage-1.0/python-deps/lib64/python2.6/site-packages:$PYTHONPATH
export PATH=/opt/mysterypackage-1.0/python-deps/bin:$PATH

使用virtualenv仍然是更好,更整洁的解决方案!

Instead of the --target option or the --install-options option, I have found that the following works well (from discussion on a bug regarding this very thing at https://github.com/pypa/pip/issues/446):

PYTHONUSERBASE=/path/to/install/to pip install --user

(Or set the PYTHONUSERBASE directory in your environment before running the command, using export PYTHONUSERBASE=/path/to/install/to)

This uses the very useful --user option but tells it to make the bin, lib, share and other directories you’d expect under a custom prefix rather than $HOME/.local.

Then you can add this to your PATH, PYTHONPATH and other variables as you would a normal installation directory.

Note that you may also need to specify the --upgrade and --ignore-installed options if any packages upon which this depends require newer versions to be installed in the PYTHONUSERBASE directory, to override the system-provided versions.

A full example:

PYTHONUSERBASE=/opt/mysterypackage-1.0/python-deps pip install --user --upgrade numpy scipy

..to install the scipy and numpy package most recent versions into a directory which you can then include in your PYTHONPATH like so (using bash and for python 2.6 on CentOS 6 for this example):

export PYTHONPATH=/opt/mysterypackage-1.0/python-deps/lib64/python2.6/site-packages:$PYTHONPATH
export PATH=/opt/mysterypackage-1.0/python-deps/bin:$PATH

Using virtualenv is still a better and neater solution!


回答 3

安装Python软件包通常仅包含一些纯Python文件。如果程序包包含数据,脚本和/或可执行文件,则它们将与纯Python文件安装在不同的目录中。

假设您的软件包没有数据/脚本/可执行文件,并且您希望Python文件进入/python/packages/package_name(而不是下面几级的某个子目录)/python/packages使用时--prefix),则可以使用一次命令:

pip install --install-option="--install-purelib=/python/packages" package_name

如果您希望所有(或大多数)包裹都放在那儿,则可以编辑 ~/.pip/pip.conf以包括:

[install]
install-option=--install-purelib=/python/packages

这样,您就不必忘记必须一次又一次地指定它。

软件包中包含的所有可执行文件/数据/脚本仍将保留其默认位置,除非您指定其他安装选项(--prefix/ --install-data/ --install-scripts等,有关详细信息,请参阅自定义安装选项)。

Installing a Python package often only includes some pure Python files. If the package includes data, scripts and or executables, these are installed in different directories from the pure Python files.

Assuming your package has no data/scripts/executables, and that you want your Python files to go into /python/packages/package_name (and not some subdirectory a few levels below /python/packages as when using --prefix), you can use the one time command:

pip install --install-option="--install-purelib=/python/packages" package_name

If you want all (or most) of your packages to go there, you can edit your ~/.pip/pip.conf to include:

[install]
install-option=--install-purelib=/python/packages

That way you can’t forget about having to specify it again and again.

Any excecutables/data/scripts included in the package will still go to their default places unless you specify addition install options (--prefix/--install-data/--install-scripts, etc., for details look at the custom installation options).


回答 4

为了将库完全安装到我想要的位置,我导航到了我想要的目录,然后使用终端

pip install mylibraryName -t . 

我从此页面获取的逻辑:https : //cloud.google.com/appengine/docs/python/googlecloudstorageclient/download

To pip install a library exactly where I wanted it, I navigated to the location I wanted the directory with the terminal then used

pip install mylibraryName -t . 

the logic of which I took from this page: https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/download


回答 5

似乎没有人提到-t选项,但最简单的是:

pip install -t <direct directory> <package>

Nobody seems to have mentioned the -t option but that the easiest:

pip install -t <direct directory> <package>

回答 6

只需在@Ian Bicking的答案中添加一点:

--user如果要在远程服务器上将一些Python软件包安装到其主目录中(没有sudo用户权限),则使用该选项指定已安装目录也可以使用。

例如,

pip install --user python-memcached

该命令会将软件包安装到PYTHONPATH中列出的目录之一。

Just add one point to @Ian Bicking’s answer:

Using the --user option to specify the installed directory also work if one wants to install some Python package into one’s home directory (without sudo user right) on remote server.

E.g.,

pip install --user python-memcached

The command will install the package into one of the directories that listed in your PYTHONPATH.


回答 7

使用python3.5和pip 9.0.3测试了这些选项:

pip install –target / myfolder [程序包]

在/ myfolder下安装所有软件包,包括依赖项。不考虑依赖包已在Python中的其他位置安装。您可以从/ myfolder / [package_name]中找到软件包。如果您有多个Python版本,则无需考虑(软件包文件夹名称中没有Python版本)。

pip install –prefix / myfolder [软件包]

检查是否已安装依赖项。将安装包到/myfolder/lib/python3.5/site-packages/[packages]

pip install –root / myfolder [软件包]

检查–prefix之类的依赖项,但安装位置将为/myfolder/usr/local/lib/python3.5/site-packages/[package_name]。

pip install –user [软件包]

会将软件包安装到$ HOME中:/home/[USER]/.local/lib/python3.5/site-packages Python会自动从此.local路径搜索,因此您无需将其放入PYTHONPATH。

=>在大多数情况下,–user是最佳选择。如果由于某种原因无法使用主文件夹,请使用–prefix。

Tested these options with python3.5 and pip 9.0.3:

pip install –target /myfolder [packages]

Installs ALL packages including dependencies under /myfolder. Does not take into account that dependent packages are already installed elsewhere in Python. You will find packages from /myfolder/[package_name]. In case you have multiple Python versions, this doesn’t take that into account (no Python version in package folder name).

pip install –prefix /myfolder [packages]

Checks are dependencies already installed. Will install packages into /myfolder/lib/python3.5/site-packages/[packages]

pip install –root /myfolder [packages]

Checks dependencies like –prefix but install location will be /myfolder/usr/local/lib/python3.5/site-packages/[package_name].

pip install –user [packages]

Will install packages into $HOME: /home/[USER]/.local/lib/python3.5/site-packages Python searches automatically from this .local path so you don’t need to put it to your PYTHONPATH.

=> In most of the cases –user is the best option to use. In case home folder can’t be used because of some reason then –prefix.


回答 8

较新的版本pip(8或更高版本)可以直接使用--prefix选项

pip install --prefix=$PREFIX_PATH package_name

在哪里$PREFIX_PATH放置lib,bin和其他顶级文件夹的安装前缀。

Newer versions of pip (8 or later) can directly use the --prefix option:

pip install --prefix=$PREFIX_PATH package_name

where $PREFIX_PATH is the installation prefix where lib, bin and other top-level folders are placed.


回答 9

pip install packageName -t pathOfDirectory

要么

pip install packageName --target pathOfDirectorty
pip install packageName -t pathOfDirectory

or

pip install packageName --target pathOfDirectorty

回答 10

补充一下已经很好的建议,因为在没有的写入权限时安装IPython时遇到了问题/usr/local

pip使用distutils进行安装,该线程讨论了依赖sys.prefix设置会导致问题的原因。

我的问题发生在IPython安装尝试在权限被拒绝的情况下写入’/ usr / local / share / man / man1’时。由于安装失败,因此似乎没有在bin目录中写入IPython文件。

使用“ –user”可以将文件写入〜/ .local。在$ PATH中添加〜/ .local / bin意味着我可以从那里使用“ ipython”。

但是,我试图为许多用户安装此程序,并已被授予对该/usr/local/lib/python2.7目录的写权限。我在该目录下创建了一个“ bin”目录,并为distutils设置了指令:

vim ~/.pydistutils.cfg

[install]
install-data=/usr/local/lib/python2.7
install-scripts=/usr/local/lib/python2.7/bin

然后((-I尽管先前失败,仍用于强制安装/.local安装):

pip install -I ipython

然后我添加/usr/local/lib/python2.7/bin$PATH

我以为我可以将其包括在内,以防其他人无法通过sudo访问的计算机上出现类似问题。

To add to the already good advice, as I had an issue installing IPython when I didn’t have write permissions to /usr/local.

pip uses distutils to do its install and this thread discusses how that can cause a problem as it relies on the sys.prefix setting.

My issue happened when the IPython install tried to write to ‘/usr/local/share/man/man1’ with Permission denied. As the install failed it didn’t seem to write the IPython files in the bin directory.

Using “–user” worked and the files were written to ~/.local. Adding ~/.local/bin to the $PATH meant I could use “ipython” from there.

However I’m trying to install this for a number of users and had been given write permission to the /usr/local/lib/python2.7 directory. I created a “bin” directory under there and set directives for distutils:

vim ~/.pydistutils.cfg

[install]
install-data=/usr/local/lib/python2.7
install-scripts=/usr/local/lib/python2.7/bin

then (-I is used to force the install despite previous failures/.local install):

pip install -I ipython

Then I added /usr/local/lib/python2.7/bin to $PATH.

I thought I’d include this in case anyone else has similar issues on a machine they don’t have sudo access to.


回答 11

不幸的是,如果您将brew与python一起使用,则pip / pip3附带的选项非常有限。您没有如上所述的–install-option,–target和–user选项。

关于pip install –user
注意事项酿造的Python禁用了正常的pip install –user。这是由于distutils中的错误,因为Homebrew编写了一个distutils.cfg来设置软件包前缀。可能的解决方法(将可执行脚本放入〜/ Library / Python /./ bin中)是: python -m pip install --user --install-option="--prefix=" <package-name>

您可能会发现此行非常麻烦。我建议使用pyenv进行管理。如果您正在使用

brew upgrade python python3

具有讽刺意味的是,您实际上是在降低点子功能。

(我之所以发布此答案,仅仅是因为我的Mac osx中的pip没有–target选项,并且我花了数小时来修复它)

If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have –install-option, –target, –user options as mentioned above.

Note on pip install –user
The normal pip install –user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is: python -m pip install --user --install-option="--prefix=" <package-name>

You might find this line very cumbersome. I suggest use pyenv for management. If you are using

brew upgrade python python3

Ironically you are actually downgrade pip functionality.

(I post this answer, simply because pip in my mac osx does not have –target option, and I have spent hours fixing it)


回答 12

v1.5.6在Python v2.7.3(GNU / Linux)上使用pip 时,option --root允许(显然)指定全局安装前缀,而与特定软件包的选项无关。试试吧,

$ pip install --root=/alternative/prefix/path package_name

With pip v1.5.6 on Python v2.7.3 (GNU/Linux), option --root allows to specify a global installation prefix, (apparently) irrespective of specific package’s options. Try f.i.,

$ pip install --root=/alternative/prefix/path package_name

回答 13

我建议遵循文档并创建〜/ .pip / pip.conf文件。注意在文档中缺少指定的标头目录,这导致以下错误:

error: install-base or install-platbase supplied, but installation scheme is incomplete

conf文件的全部工作内容是:

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data

不幸的是我可以安装,但是当尝试卸载pip时,告诉我没有用于卸载过程的软件包。

I suggest to follow the documentation and create ~/.pip/pip.conf file. Note in the documentation there are missing specified header directory, which leads to following error:

error: install-base or install-platbase supplied, but installation scheme is incomplete

The full working content of conf file is:

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data

Unfortunatelly I can install, but when try to uninstall pip tells me there is no such package for uninstallation process…. so something is still wrong but the package goes to its predefined location.


回答 14

pip install /path/to/package/

现在是可能的。

与使用-e--editable标志的区别在于,-e链接指向软件包的保存位置(即下载文件夹),而不是将其安装到python路径中。

这意味着,如果您将软件包删除/移动到另一个文件夹,则将无法使用它。

pip install /path/to/package/

is now possible.

The difference with this and using the -e or --editable flag is that -e links to where the package is saved (i.e. your downloads folder), rather than installing it into your python path.

This means if you delete/move the package to another folder, you won’t be able to use it.


回答 15

我找到了简单的方法

pip3 install "package_name" -t "target_dir"

来源-https://pip.pypa.io/en/stable/reference/pip_install/

我用pip3尝试了,它有效!

I found simple way

pip3 install "package_name" -t "target_dir"

source – https://pip.pypa.io/en/stable/reference/pip_install/

I tried it with pip3 and it works!


如何在Ubuntu上通过pip安装python3版本的软件包?

问题:如何在Ubuntu上通过pip安装python3版本的软件包?

我都python2.7python3.2安装Ubuntu 12.04
符号链接python链接到python2.7

当我输入:

sudo pip install package-name

它将默认安装的python2版本package-name

一些软件包同时支持python2python3
如何安装via python3版本?package-namepip

I have both python2.7 and python3.2 installed in Ubuntu 12.04.
The symbolic link python links to python2.7.

When I type:

sudo pip install package-name

It will default install python2 version of package-name.

Some package supports both python2 and python3.
How to install python3 version of package-name via pip?


回答 0

您可能需要构建virtualenvpython3的,然后在激活virtualenv之后安装python3的软件包。这样您的系统就不会混乱了:)

可能是这样的:

virtualenv -p /usr/bin/python3 py3env
source py3env/bin/activate
pip install package-name

You may want to build a virtualenv of python3, then install packages of python3 after activating the virtualenv. So your system won’t be messed up :)

This could be something like:

virtualenv -p /usr/bin/python3 py3env
source py3env/bin/activate
pip install package-name

回答 1

Ubuntu 12.10+和Fedora 13+都有一个名为的软件包python3-pip,它将安装pip-3.2(或pip-3.3pip-3.4或者pip3对于较新的版本),而无需花钱。


我碰到了这一点,并在不需要like wget或virtualenvs的情况下解决了这个问题(假设Ubuntu 12.04):

  1. 安装软件包python3-setuptools:运行sudo aptitude install python3-setuptools,这将给您命令easy_install3
  2. 使用Python 3的setuptools安装run pip:run sudo easy_install3 pip,这将为您提供pip-3.2类似于kev解决方案的命令。
  3. 安装您的PyPI软件包:运行sudo pip-3.2 install <package>(将python软件包安装到基本系统中当然需要root)。
  4. 利润!

Ubuntu 12.10+ and Fedora 13+ have a package called python3-pip which will install pip-3.2 (or pip-3.3, pip-3.4 or pip3 for newer versions) without needing this jumping through hoops.


I came across this and fixed this without needing the likes of wget or virtualenvs (assuming Ubuntu 12.04):

  1. Install package python3-setuptools: run sudo aptitude install python3-setuptools, this will give you the command easy_install3.
  2. Install pip using Python 3’s setuptools: run sudo easy_install3 pip, this will give you the command pip-3.2 like kev’s solution.
  3. Install your PyPI packages: run sudo pip-3.2 install <package> (installing python packages into your base system requires root, of course).
  4. Profit!

回答 2

简短答案

sudo apt-get install python3-pip
sudo pip3 install MODULE_NAME

资料来源:Shashank Bharadwaj的评论

长答案

简短的答案仅适用于较新的系统。在某些版本的Ubuntu上,命令为pip-3.2

sudo pip-3.2 install MODULE_NAME

如果不起作用,则此方法适用于任何Linux发行版和受支持的版本

sudo apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py | sudo python3
sudo pip3 install MODULE_NAME

如果没有curl,请使用wget。如果没有sudo,请切换到root。如果pip3symlink不存在,请检查类似pip-3的内容。X

许多python软件包也需要dev软件包,因此也要安装它:

sudo apt-get install python3-dev

来源:
python使用pip安装软件包
Pip最新安装

如果您想要更高版本的Python,也请查看Tobu的答案

我想补充一点,使用虚拟环境通常是开发python应用程序的首选方法,因此@felixyan答案可能是理想世界中的最佳选择。但是,如果您真的想在全球范围内安装该软件包,或者需要在不激活虚拟环境的情况下频繁测试/使用该软件包,那么我认为将其作为全局软件包安装是可行的方法。

Short Answer

sudo apt-get install python3-pip
sudo pip3 install MODULE_NAME

Source: Shashank Bharadwaj’s comment

Long Answer

The short answer applies only on newer systems. On some versions of Ubuntu the command is pip-3.2:

sudo pip-3.2 install MODULE_NAME

If it doesn’t work, this method should work for any Linux distro and supported version:

sudo apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py | sudo python3
sudo pip3 install MODULE_NAME

If you don’t have curl, use wget. If you don’t have sudo, switch to root. If pip3 symlink does not exists, check for something like pip-3.X

Much python packages require also the dev package, so install it too:

sudo apt-get install python3-dev

Sources:
python installing packages with pip
Pip latest install

Check also Tobu’s answer if you want an even more upgraded version of Python.

I want to add that using a virtual environment is usually the preferred way to develop a python application, so @felixyan answer is probably the best in an ideal world. But if you really want to install that package globally, or if need to test / use it frequently without activating a virtual environment, I suppose installing it as a global package is the way to go.


回答 3

好吧,在ubuntu 13.10 / 14.04上,情况有所不同。

安装

$ sudo apt-get install python3-pip

安装套件

$ sudo pip3 install packagename

pip-3.3 install

Well, on ubuntu 13.10/14.04, things are a little different.

Install

$ sudo apt-get install python3-pip

Install packages

$ sudo pip3 install packagename

NOT pip-3.3 install


回答 4

安装最新pip2/ pip3和相应软件包的最简单方法:

curl https://bootstrap.pypa.io/get-pip.py | python2
pip2 install package-name    

curl https://bootstrap.pypa.io/get-pip.py | python3
pip3 install package-name

注意:请按以下方式运行这些命令root

The easiest way to install latest pip2/pip3 and corresponding packages:

curl https://bootstrap.pypa.io/get-pip.py | python2
pip2 install package-name    

curl https://bootstrap.pypa.io/get-pip.py | python3
pip3 install package-name

Note: please run these commands as root


回答 5

尝试安装pylab时遇到了同样的问题,并且找到了此链接

因此,我在Python 3中安装pylab所做的工作是:

python3 -m pip install SomePackage

它运行正常,并且如您在链接中所见,您可以为每个Python版本执行此操作,因此我想这可以解决您的问题。

I had the same problem while trying to install pylab, and I have found this link

So what I have done to install pylab within Python 3 is:

python3 -m pip install SomePackage

It has worked properly, and as you can see in the link you can do this for every Python version you have, so I guess this solves your problem.


回答 6

旧的问题,但没有一个答案令我满意。我的系统之一正在运行Ubuntu 12.04 LTS,由于某种原因,没有软件包python3-pippython-pipPython3。所以这就是我所做的(所有命令均以root用户身份执行):

  • setuptools如果没有,请安装Python3。

    apt-get install python3-setuptools

    要么

    aptitude install python3-setuptools
  • 在Python 2.4+中,您可以使用调用easy_install特定的Python版本python -m easy_install。因此,pip对于Python 3,可以通过以下方式安装:

    python3 -m easy_install pip
  • 就是这样,您使用的是pipPython3。现在只需调用pip特定版本的Python即可安装Python 3的软件包。例如,在系统上安装了Python 3.2的情况下,我使用了:

    pip-3.2 install [package]

Old question, but none of the answers satisfies me. One of my systems is running Ubuntu 12.04 LTS and for some reason there’s no package python3-pip or python-pip for Python 3. So here is what I’ve done (all commands were executed as root):

  • Install setuptools for Python3 in case you haven’t.

    apt-get install python3-setuptools
    

    or

    aptitude install python3-setuptools
    
  • With Python 2.4+ you can invoke easy_install with specific Python version by using python -m easy_install. So pip for Python 3 could be installed by:

    python3 -m easy_install pip
    
  • That’s it, you got pip for Python 3. Now just invoke pip with the specific version of Python to install package for Python 3. For example, with Python 3.2 installed on my system, I used:

    pip-3.2 install [package]
    

回答 7

如果您在两个python中都安装了pip,并且都在路径中,则只需使用:

$ pip-2.7 install PACKAGENAME
$ pip-3.2 install PACKAGENAME

参考文献:

这是问题的重复#2812520

If you have pip installed in both pythons, and both are in your path, just use:

$ pip-2.7 install PACKAGENAME
$ pip-3.2 install PACKAGENAME

References:

This is a duplicate of question #2812520


回答 8

如果您的系统python2是默认设置,请使用以下命令将软件包安装到python3

$ python3 -m pip install <package-name>

If your system has python2 as default, use below command to install packages to python3

$ python3 -m pip install <package-name>


回答 9

很简单:

sudo aptitude install python3-pip
pip-3.2 install --user pkg

如果要使用Python 3.3(自Ubuntu 12.10起不是默认设置):

sudo aptitude install python3-pip python3.3
python3.3 -m pip.runner install --user pkg

Easy enough:

sudo aptitude install python3-pip
pip-3.2 install --user pkg

If you want Python 3.3, which isn’t the default as of Ubuntu 12.10:

sudo aptitude install python3-pip python3.3
python3.3 -m pip.runner install --user pkg

回答 10

您也可以直接运行pip3 install packagename,而不是pip

You can alternatively just run pip3 install packagename instead of pip,


回答 11

首先,您需要为想要的Python 3安装安装pip。然后,您运行该pip为该Python版本安装软件包。

由于您在/ usr / bin中同时拥有pip和python 3,因此我假定它们都已通过某种程序包管理器安装。该软件包管理器还应具有Python 3点。那是您应该安装的那个。

Felix对virtualenv的推荐是一个很好的建议。如果您只是测试,或者正在开发,则不应将软件包安装在系统python中。在这些情况下,使用virtualenv甚至构建自己的Python进行开发会更好。

但如果你真的希望在系统Python安装该软件包,为Python 3安装PIP是要走的路。

Firstly, you need to install pip for the Python 3 installation that you want. Then you run that pip to install packages for that Python version.

Since you have both pip and python 3 in /usr/bin, I assume they are both installed with a package manager of some sort. That package manager should also have a Python 3 pip. That’s the one you should install.

Felix’ recommendation of virtualenv is a good one. If you are only testing, or you are doing development, then you shouldn’t install the package in the system python. Using virtualenv, or even building your own Pythons for development, is better in those cases.

But if you actually do want to install this package in the system python, installing pip for Python 3 is the way to go.


回答 12

尽管该问题与Ubuntu有关,但我还是要说我在Mac上,而我的python命令默认为Python 2.7.5。我也有Python 3,可通过进行访问python3,因此知道了pip包的起源,我就下载了pip包并sudo python3 setup.py install针对它发布了,当然,只有Python 3现在在其站点包中包含了此模块。希望这有助于流浪的Mac陌生人。

Although the question relates to Ubuntu, let me contribute by saying that I’m on Mac and my python command defaults to Python 2.7.5. I have Python 3 as well, accessible via python3, so knowing the pip package origin, I just downloaded it and issued sudo python3 setup.py install against it and, surely enough, only Python 3 has now this module inside its site packages. Hope this helps a wandering Mac-stranger.


回答 13

直接执行pip二进制文件。

首先找到所需的PIP版本。

jon-mint python3.3 # whereis ip
ip: /bin/ip /sbin/ip /usr/share/man/man8/ip.8.gz /usr/share/man/man7/ip.7.gz

然后执行。

jon-mint python3.3 # pip3.3 install pexpect
Downloading/unpacking pexpect
  Downloading pexpect-3.2.tar.gz (131kB): 131kB downloaded
  Running setup.py (path:/tmp/pip_build_root/pexpect/setup.py) egg_info for package pexpect

Installing collected packages: pexpect
  Running setup.py install for pexpect

Successfully installed pexpect
Cleaning up...

Execute the pip binary directly.

First locate the version of PIP you want.

jon-mint python3.3 # whereis ip
ip: /bin/ip /sbin/ip /usr/share/man/man8/ip.8.gz /usr/share/man/man7/ip.7.gz

Then execute.

jon-mint python3.3 # pip3.3 install pexpect
Downloading/unpacking pexpect
  Downloading pexpect-3.2.tar.gz (131kB): 131kB downloaded
  Running setup.py (path:/tmp/pip_build_root/pexpect/setup.py) egg_info for package pexpect

Installing collected packages: pexpect
  Running setup.py install for pexpect

Successfully installed pexpect
Cleaning up...

回答 14

  1. 您应该安装所有依赖项:

    sudo apt-get install build-essential python3-dev python3-setuptools python3-numpy python3-scipy libatlas-dev libatlas3gf-base

  2. 安装pip3(如果已安装,请查看步骤3):

    sudo apt-get install python3-pip

  3. 我通过pip3安装scikit-learn

    pip3 install -U scikit-learn

  4. 打开您的终端并输入python3环境,键入import sklearn以进行检查。

祝你好运!

  1. You should install ALL dependencies:

    sudo apt-get install build-essential python3-dev python3-setuptools python3-numpy python3-scipy libatlas-dev libatlas3gf-base

  2. Install pip3(if you have installed, please look step 3):

    sudo apt-get install python3-pip

  3. Iinstall scikit-learn by pip3

    pip3 install -U scikit-learn

  4. Open your terminal and entry python3 environment, type import sklearn to check it.

Gook Luck!


回答 15

要为python3安装pip,请使用pip3而不是pip。在Ubuntu 18.08 Bionic中安装python

须藤apt-get install python3.7

在ubuntu中安装所需的pip软件包

须藤apt-get install python3-pip

To install pip for python3 use should use pip3 instead of pip. To install python in ubuntu 18.08 bionic

sudo apt-get install python3.7

To install the required pip package in ubuntu

sudo apt-get install python3-pip


回答 16

安装python3的另一种方法是使用wget。以下是安装步骤。

wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install

另外,可以使用

echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc

现在打开一个新终端并输入py并按Enter。

Another way to install python3 is using wget. Below are the steps for installation.

wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install

Also,one can create an alias for the same using

echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc

Now open a new terminal and type py and press Enter.


bash:pip:找不到命令

问题:bash:pip:找不到命令

我下载了pip并运行python setup.py install,一切正常。本教程的下一步是运行,pip install <lib you want>但是甚至在尝试在线查找任何内容之前,我都会收到错误消息“ bash:pip:not found”。

这是在Mac OS X上,这也是我的新手,因此我假设有些路径设置在运行setup.py时未正确设置。我该如何进一步调查?我需要检查什么才能更好地了解问题的确切原因?

编辑:我也尝试过为Mac安装Python 2.7,希望友好的安装过程能够完成所有工作,例如编辑PATH,以及根据教程使一切正常工作所需的其他一切,但这是行不通的。安装运行后,“ python”仍然运行python 2.6,并且PATH未更新。

I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error “bash: pip: command not found”.

This is on Mac OS X, which I’m new too, so I’m assuming there’s some kind of path setting that was not set correctly when I ran setup.py. How can I investigate further? What do I need to check to get a better idea of the exact cause of the problem?

EDIT: I also tried installing Python 2.7 for Mac in the hopes that the friendly install process would do any housekeeping like editing PATH and whatever else needs to happy for everything to work according to the tutorials, but this didn’t work. After installing is running ‘python’ still ran Python 2.6 and PATH was not updated.


回答 0

为什么不这样做,sudo easy_install pip或者这是否适用于python 2.6 sudo easy_install-2.6 pip

这将使用默认的python软件包安装程序系统安装pip,并同时为您节省了手动设置的麻烦。

这将允许您运行pippython软件包安装命令,因为它将与系统python一起安装。我也建议您在使用virtualenv软件包和模式时获得点子。:)

Why not just do sudo easy_install pip or if this is for python 2.6 sudo easy_install-2.6 pip?

This installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time.

This will allow you to then run the pip command for python package installation as it will be installed with the system python. I also recommend once you have pip using the virtualenv package and pattern. :)


回答 1

使用setuptools安装pip

sudo easy_install pip

(我知道答案的上面部分对于klobucar来说是多余的,但是我还不能添加评论),所以这是一个解决方案 sudo: easy_install: command not found关于Debian / Ubuntu:

sudo apt-get install python-setuptools

另外,对于python3,请使用easy_install3python3-setuptools

Use setuptools to install pip:

sudo easy_install pip

(I know the above part of my answer is redundant with klobucar’s, but I can’t add comments yet), so here’s an answer with a solution to sudo: easy_install: command not found on Debian/Ubuntu:

sudo apt-get install python-setuptools

Also, for python3, use easy_install3 and python3-setuptools.


回答 2

首先:尝试使用pip3而不是pip。例:

pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

pip3应该与Python3.x一起自动安装。该文档尚未更新,因此例如在安装Flask时,将说明中的pip替换为pip3即可。

现在,如果这不起作用,则可能必须单独安装pip。

First of all: try pip3 instead of pip. Example:

pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

pip3 should be installed automatically together with Python3.x. The documentation hasn’t been updated, so simply replace pip by pip3 in the instructions, when installing Flask for example.

Now, if this doesn’t work, you might have to install pip separately.


回答 3

更新:访问正确的pip安装以进行正确的python安装的一种更可靠的现代方法是使用语法python -m pip

原始答案

pip会将其自身安装到您的python安装位置的bin中。它还应创建一个指向更常见位置的符号链接,例如/usr/local/bin/pip

您可以编辑~/.profilePATH并将其更新为include /Library/Frameworks/Python.framework/Versions/2.6/bin,也可以在路径中的已知位置创建指向它的符号链接。

如果您执行以下操作: echo $PATH,您应该看到当前正在搜索的路径。如果/usr/local/bin位于PATH中,则可以执行以下操作:

ln -s /Library/Frameworks/Python.framework/Versions/2.6/bin/pip /usr/local/bin

我会选择将python bin添加到$ PATH变量中。

Update: A more reliable modern way to access the right pip install for the right python install is to use the syntax python -m pip.

Original Answer

pip would install itself into the bin of your python installation location. It also should create a symlink to some more common location like /usr/local/bin/pip

You can either edit your ~/.profile and update your PATH to include /Library/Frameworks/Python.framework/Versions/2.6/bin, or you could create a symlink to it in a place that you know is in your path.

If you do: echo $PATH, you should see the paths currently being searched. If /usr/local/bin is in your PATH, you can do:

ln -s /Library/Frameworks/Python.framework/Versions/2.6/bin/pip /usr/local/bin

I would opt for adding the python bin to your $PATH variable.


回答 4

按照给定安装Python最新版本 这里

它具有许多下载链接,例如numpy和scipy

然后转到终端并输入以下命令:

sudo easy_install pip

对于Python安装包,请检查此

安装软件包的要求本节介绍在安装其他Python软件包之前应遵循的步骤。

安装pip,setuptools和wheel如果从python.org安装了Python 2> = 2.7.9或Python 3> = 3.4,则已经具有pip和setuptools,但需要升级到最新版本:

在Linux或OS X上:

pip install -U pip setuptools在Windows上:

python -m pip install -U pip setuptools如果您正在Linux上使用由系统软件包管理器(例如“ yum”,“ apt-get”等)管理的Python安装,并且您想使用系统软件包管理器要安装或升级pip,请参阅使用Linux软件包管理器安装pip / setuptools / wheel

除此以外:

安全下载get-pip.py 1

运行python get-pip.py。2这将安装或升级点子。另外,如果尚未安装setuptools和wheel,它将安装setuptools和wheel。

Install Python latest version as given here

It has many download links like numpy and scipy

Then go to terminal and enter following command:-

sudo easy_install pip

For Python install packages check this

Requirements for Installing Packages This section describes the steps to follow before installing other Python packages.

Install pip, setuptools, and wheel If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:

On Linux or OS X:

pip install -U pip setuptools On Windows:

python -m pip install -U pip setuptools If you’re using a Python install on Linux that’s managed by the system package manager (e.g “yum”, “apt-get” etc…), and you want to use the system package manager to install or upgrade pip, then see Installing pip/setuptools/wheel with Linux Package Managers

Otherwise:

Securely Download get-pip.py 1

Run python get-pip.py. 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.


回答 5

我必须承认对python绝对是新手,我只需要一件事:awscli。我在下载python 3.xx时遇到了这个问题-pip:命令未找到

遵循下载AWS CLI的说明后,我进行了更改

pip install awscli

pip3 install awscli

运行了正确的版本。

我在计算机上做了一个别名,以在输入python的同时运行python3,这通常会运行系统版本2.7。我现在不确定这是个好主意。我想我只是按照他们想要的那样输入命令

I have to admit to being absolutely new to python, which I only need for one thing: awscli. I encountered this problem having downloaded python 3.x.x – pip: command not found

Whilst following the instructions for downloading the AWS cli I changed

pip install awscli

to

pip3 install awscli

which ran the correct version.

I’ve made an alias on my machine to run python3 whilst typing python, which would normally run the system version 2.7. I’m not sure this is a good idea now. I think I’ll just type in the commands as they intended them to be


回答 6

请参阅“ 如何安装Pip”一文,以了解更多信息。

截至2019年,

提供下载get-pip.py https://pip.pypa.io使用下面的命令:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

使用以下命令运行get-pip.py:
sudo python get-pip.py

完成安装后,运行此命令以检查是否安装了pip。
pip --version

安装pip后,删除get-pip.py文件。
rm get-pip.py

点子网站

Check out How to Install Pip article article for more information.

As of 2019,

Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run get-pip.py using the following command:
sudo python get-pip.py

After you done installing, run this command to check if pip is installed.
pip --version

Remove get-pip.py file after installing pip.
rm get-pip.py

Pip website


回答 7

使用apt-get安装会在整个系统范围内安装pip,而不仅仅是为您的用户安装本地系统。尝试使用此命令使pip在您的系统上运行…

$ sudo apt-get install python-pip python-dev build-essential

然后pip将被安装而没有任何问题,您将可以使用“ sudo pip …”。

Installing using apt-get installs a system wide pip, not just a local one for your user. Try this command to get pip running on your system …

$ sudo apt-get install python-pip python-dev build-essential

Then pip will be installed without any issues and you will be able to use “sudo pip…”.


回答 8

不推荐使用大多数安装PIP的方法。这是最新的(2019)解决方案。请下载get-pip脚本

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

运行脚本

sudo python get-pip.py

Most of the methods to install PIP are deprecated. Here is the latest (2019) solution. Please download get-pip script

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run the script

sudo python get-pip.py

回答 9

我花了很长时间浏览本页上的所有答案,但在s-walsh对OP问题的评论中找到了一个对我有用的

答案是使用pip3:

$ pip3 install <name-of-install>

I spent ages going through all the answers on this page but found the one that worked for me in the comments of the OP question by s-walsh

The answer is to use pip3:

$ pip3 install <name-of-install>

回答 10

解决:

  1. 将此行添加到〜/ .bash_profile

    导出PATH =“ / usr / local / bin:$ PATH”

  2. 在终端窗口中,运行

    来源〜/ .bash_profile

To solve:

  1. Add this line to ~/.bash_profile

    export PATH=”/usr/local/bin:$PATH”

  2. In a terminal window, run

    source ~/.bash_profile


回答 11

它可能是root权限。我尝试退出root登录,使用

sudo su -l root
pip <command>

这对我行得通

It might be the root permission. I tried exit root login, use

sudo su -l root
pip <command>

that works for me


回答 12

安装Homebrew,打开Terminal或您喜欢的OSX终端仿真器并运行

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

将Homebrew目录插入PATH环境变量的顶部。您可以通过在〜/ .profile文件底部添加以下行来完成此操作

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

现在,我们可以安装Python 2.7:

$ brew install python

获取点子存储库:

$ git clone https://github.com/pypa/pip

安装点:

$sudo easy_install pip

install Homebrew, open Terminal or your favorite OSX terminal emulator and run

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your ~/.profile file

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

Now, we can install Python 2.7:

$ brew install python

Get pip repository:

$ git clone https://github.com/pypa/pip

install pip:

$sudo easy_install pip

回答 13

如果您正在运行Python 3.5,请运行以下终端命令:

sudo pip3 install -U nltk

终端中的任何其他pip命令都将类似:

pip3 install --upgrade pip
sudo pip3 install -U numpy ::

If you are running Python 3.5, run the following terminal command:

sudo pip3 install -U nltk

Any other pip commands in terminal would be similar:

pip3 install --upgrade pip
sudo pip3 install -U numpy ::

回答 14

python默认情况下安装它,但如果未安装,则可以使用以下cmd手动安装(仅适用于linux)

对于python3:

sudo apt install python3-pip 

对于python2

sudo apt install python-pip 

希望它的帮助。

python install it by default but if not install you can install it manual use following cmd (for linux only )

for python3 :

sudo apt install python3-pip 

for python2

sudo apt install python-pip 

hope its help.


回答 15

避免sudo

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

从:

http://www.pip-command-not-found.com

Avoiding sudo:

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

From:

http://www.pip-command-not-found.com


回答 16

CentOS 7用户可以使用:

yum install python-pip

virtualenv如果您使用的是点子,也建议使用。可以用相同的方式添加它:

yum install python-virtualenv

CentOS 7 users can just use:

yum install python-pip

Also recommend using virtualenv if you’re using pip. It can be added in the same way:

yum install python-virtualenv

回答 17

假设您有互联网,请参阅: https //pip.pypa.io/en/stable/installing/

基本上运行:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

assuming you have internet see: https://pip.pypa.io/en/stable/installing/

basically run:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

and

python get-pip.py

回答 18

(上下文:我的操作系统是使用AWS的Amazon linux。它看起来与RedHat类似,但看起来有所减少。)

退出外壳,然后打开一个新的外壳。pip命令现在可以使用。

这就是解决此位置问题的方法。

您可能还想知道:然后需要像下面的示例(例如jupyter)那样编写用于安装软件的pip命令,以便在我的系统上正常工作:

pip安装jupyter –user

具体来说,请注意缺少sudo以及–user的存在

如果pip文档对所有这些都说了话,那将是非常不错的,但是我猜这将需要输入更多的字符。

(Context: My OS is Amazon linux using AWS. It seems similar to RedHat but it’s stripped down a bit, it seems.)

Exit the shell, then open a new shell. The pip command now works.

That’s what solved the problem at this location.

You might want to know as well: The pip commands to install software then needed to be written like this example (jupyter for example) to work correctly on my system:

pip install jupyter –user

Specifically, note the lack of sudo, and the presence of –user

Would be real nice if pip docs had said anything about all this, but that would take typing in more characters I guess.


回答 19

不知道为什么以前没有提到过,但是唯一对我有用的(在我的NVIDIA Xavier上)是:

sudo apt-get install python3-pip

(或sudo apt-get install python-pip对于python 2)

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)


回答 20

通过升级python 3解决了这个问题 brew upgrade python:现在我可以这样做:

pip3 install  <package>  

==> python
Python has been installed as
  /usr/local/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have 

Solved this by upgrading python 3 brew upgrade python: Now i can just do:

pip3 install  <package>  

==> python
Python has been installed as
  /usr/local/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have 

回答 21

问题似乎是您的python版本和要安装的库yoıu版本不匹配。例如:如果Django是Django3,而您的python版本是2.7,则可能会收到此错误。

“安装运行后,’python’仍运行Python 2.6,并且PATH未更新。”

1-安装最新版本的Python 2-手动将PATH更改为python38并进行比较。3-尝试重新安装。

我解决了此问题,方法是使用最新版本的Python手动替换PATH。对于Windows:; C:\ python38 \ Scripts

The problem seems that your python version and the library yoıu want to install is not matching versionally. Ex: If Django is Django3 and your python version is 2.7, you may get this error.

“After installing is running ‘python’ still ran Python 2.6 and PATH was not updated.”

1- Install latest version of Python 2- Change your PATH manually as python38 and compare them. 3- Try to reinstall.

I solved this problem as replacing PATH manually with the latest version of Python. As for Windows: ;C:\python38\Scripts


回答 22

我为克服这个问题所做的是sudo apt install python-pip

原来我的虚拟机尚未安装pip。可以想象其他人也可能有这种情况。

What I did to overcome this was sudo apt install python-pip.

It turned out my virtual machine did not have pip installed yet. It’s conceivable that other people could have this scenario too.


回答 23

python-pip在更新pip编辑后使用过时版本的pip(9.0),当前发布的pip版本为(18.0),请/usr/bin/pip替换此导入:

from pip import main

from pip._internal import main

这适用于pip 18.0问题是pip更改main功能名称重复为/usr/bin/pip3/usr/bin/pip2

还认为/usr/local/lib/[your_python_version]/dist-packages/pip/__main__.py它应该与/usr/bin/pip

python-pip use obsolete version of pip (9.0) current post pip version is (18.0) after updating pip edit /usr/bin/pip replace this import:

from pip import main

to

from pip._internal import main

this working for pip 18.0 problem is pip change main function name repeat for /usr/bin/pip3 and /usr/bin/pip2

also view /usr/local/lib/[your_python_version]/dist-packages/pip/__main__.py It should be the same as /usr/bin/pip


回答 24

请执行以下操作:

sudo apt update
sudo apt install python3-pip
source ~/.bashrc

这肯定会安装pip及其所有依赖项。PS这是用于python 3,如果要使用python 2,请从第二个命令中将python3替换为python

sudo apt install python-pip

Do following:

sudo apt update
sudo apt install python3-pip
source ~/.bashrc

This will surely install pip with all its dependencies. PS this is for python 3 if you want for python 2 replace python3 from the second command to python

sudo apt install python-pip

回答 25

要解决Mac中的“ bash:pip:找不到命令 ”问题

在Mac 1上发现两个版本是2.7,另一个是3.7

  • 当我说sudo easy_install pip时,pip在2.7下安装

  • 当我说sudo easy_install-3.7 pip时,pip已安装在3.7下

但是,每当我需要进行pip install时,我都想在python3.7下安装该软件包,因此我在.bash_profile中设置了一个别名(alias pip = pip3)。

所以现在,每当我进行pip install时,都会在python3.7下安装

To overcome the issue “bash: pip: command not found” in Mac

Found two versions on Mac 1 is 2.7 and the other is 3.7

  • when I say sudo easy_install pip, pip got installed under 2.7

  • when I say sudo easy_install-3.7 pip, pip got installed under 3.7

But, whenever I would require to do pip install , I wanted to install the package under python3.7, so I have set an alias (alias pip=pip3)in .bash_profile

so now, whenever I do pip install , it gets installed under python3.7


回答 26

更新的安装命令为pip3

sudo apt-get install python3-pip

The updated command for installing pip3 is :

sudo apt-get install python3-pip

查找使用easy_install / pip安装的所有软件包?

问题:查找使用easy_install / pip安装的所有软件包?

有没有办法找到所有通过easy_install或pip安装的Python PyPI软件包?我的意思是,排除分发工具已经安装的所有东西(在本例中为Debian上的apt-get)。

Is there a way to find all Python PyPI packages that were installed with easy_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).


回答 0

pip freeze将输出已安装软件包及其版本的列表。它还允许您将那些程序包写入文件,以便以后用于设置新环境。

https://pip.pypa.io/zh_CN/stable/reference/pip_freeze/#pip-freeze

pip freeze will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment.

https://pip.pypa.io/en/stable/reference/pip_freeze/#pip-freeze


回答 1

从1.3版本的pip开始,您现在可以使用 pip list

它具有一些有用的选项,包括显示过期软件包的能力。这是文档:https : //pip.pypa.io/en/latest/reference/pip_list/

As of version 1.3 of pip you can now use pip list

It has some useful options including the ability to show outdated packages. Here’s the documentation: https://pip.pypa.io/en/latest/reference/pip_list/


回答 2

如果有人想知道您可以使用“ pip show”命令。

pip show [options] <package>

这将列出给定软件包的安装目录。

If anyone is wondering you can use the ‘pip show’ command.

pip show [options] <package>

This will list the install directory of the given package.


回答 3

如果Debian在pip install默认目标上的行为类似于最近的Ubuntu版本,那就太简单了:它安装到(/usr/local/lib/而不是/usr/libapt默认目标))。检查/ubuntu/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

我是ArchLinux用户,在尝试pip时遇到了同样的问题。这是我在Arch中解决问题的方法。

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

此处的关键是/usr/lib/python2.7/site-packages,这是pip安装到的目录YMMV。pacman -Qo是如何Arch的PAC卡格男人几岁检查该文件的所有权。No package是没有包拥有文件时返回的一部分error: No package owns $FILENAME。整蛊解决方法:我询问有关__init__.py,因为pacman -Qo有点懵,当涉及到目录:(

为了在其他发行版中做到这一点,您必须找出在哪里pip安装东西(仅仅sudo pip install是东西),如何查询文件的所有权(Debian / Ubuntu方法是dpkg -S)以及“没有软件包拥有该路径”返回(Debian)是什么。 / Ubuntu是no path found matching pattern)。Debian / Ubuntu用户,请注意:dpkg -S如果给它一个符号链接,它将失败。只需先使用解决即可realpath。像这样:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora用户可以尝试(感谢@eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

If Debian behaves like recent Ubuntu versions regarding pip install default target, it’s dead easy: it installs to /usr/local/lib/ instead of /usr/lib (apt default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

I am an ArchLinux user and as I experimented with pip I met this same problem. Here’s how I solved it in Arch.

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

Key here is /usr/lib/python2.7/site-packages, which is the directory pip installs to, YMMV. pacman -Qo is how Arch’s pac kage man ager checks for ownership of the file. No package is part of the return it gives when no package owns the file: error: No package owns $FILENAME. Tricky workaround: I’m querying about __init__.py because pacman -Qo is a little bit ignorant when it comes to directories :(

In order to do it for other distros, you have to find out where pip installs stuff (just sudo pip install something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S) and what is the “no package owns that path” return (Debian/Ubuntu is no path found matching pattern). Debian/Ubuntu users, beware: dpkg -S will fail if you give it a symbolic link. Just resolve it first by using realpath. Like this:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora users can try (thanks @eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

回答 4

从…开始:

$ pip list

列出所有软件包。找到所需的软件包后,请使用:

$ pip show <package-name>

这将显示有关此软件包的详细信息,包括其文件夹。如果您已经知道软件包名称,则可以跳过第一部分

点击这里对PIP显示更多的信息,这里的PIP列表的详细信息。

例:

$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: jupyter@googlegroups.org
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel    

Start with:

$ pip list

To list all packages. Once you found the package you want, use:

$ pip show <package-name>

This will show you details about this package, including its folder. You can skip the first part if you already know the package name

Click here for more information on pip show and here for more information on pip list.

Example:

$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: jupyter@googlegroups.org
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel    

回答 5

pip.get_installed_distributions() 将给出已安装软件包的列表

import pip
from os.path import join

for package in pip.get_installed_distributions():
    print(package.location) # you can exclude packages that's in /usr/XXX
    print(join(package.location, package._get_metadata("top_level.txt"))) # root directory of this package

pip.get_installed_distributions() will give a list of installed packages

import pip
from os.path import join

for package in pip.get_installed_distributions():
    print(package.location) # you can exclude packages that's in /usr/XXX
    print(join(package.location, package._get_metadata("top_level.txt"))) # root directory of this package

回答 6

下面的程序有点慢,但是它给出了一个可以识别的格式良好的软件包列表pip。也就是说,并不是所有的人都通过“ pip”安装的,但是所有的人都应该能够通过pip进行升级。

$ pip search . | egrep -B1 'INSTALLED|LATEST'

之所以慢,是因为它列出了整个pypi存储库的内容。我提交了一张票,建议pip list提供类似的功能,但效率更高。

样本输出:(将搜索限制为所有子集而不是“。”。)

$ pip search selenium | egrep -B1 'INSTALLED|LATEST'

selenium                  - Python bindings for Selenium
  INSTALLED: 2.24.0
  LATEST:    2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
  INSTALLED: 1.0.1 (latest)
$

The below is a little slow, but it gives a nicely formatted list of packages that pip is aware of. That is to say, not all of them were installed “by” pip, but all of them should be able to be upgraded by pip.

$ pip search . | egrep -B1 'INSTALLED|LATEST'

The reason it is slow is that it lists the contents of the entire pypi repo. I filed a ticket suggesting pip list provide similar functionality but more efficiently.

Sample output: (restricted the search to a subset instead of ‘.’ for all.)

$ pip search selenium | egrep -B1 'INSTALLED|LATEST'

selenium                  - Python bindings for Selenium
  INSTALLED: 2.24.0
  LATEST:    2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
  INSTALLED: 1.0.1 (latest)
$

回答 7

除了@Paul Woolcock的答案,

pip freeze > requirements.txt

将在当前位置的活动环境中创建一个包含所有已安装软件包以及已安装版本号的需求文件。跑步

pip install -r requirements.txt

将安装需求文件中指定的软件包。

Adding to @Paul Woolcock’s answer,

pip freeze > requirements.txt

will create a requirements file with all installed packages along with the installed version numbers in the active environment at the current location. Running

pip install -r requirements.txt

will install the packages specified in the requirements file.


回答 8

较新版本的pip可以通过pip list -lpip freeze -l--list)执行OP所需的操作。
在Debian上(至少),手册页对此没有明确说明,而我只是在假设该功能必须存在的情况下才发现了with pip list --help

最近有评论表明此功能在文档或现有答案中均不明显(尽管有人暗示),所以我认为应该发布。我本来希望以此作为评论,但我没有信誉点。

Newer versions of pip have the ability to do what the OP wants via pip list -l or pip freeze -l (--list).
On Debian (at least) the man page doesn’t make this clear, and I only discovered it – under the assumption that the feature must exist – with pip list --help.

There are recent comments that suggest this feature is not obvious in either the documentation or the existing answers (although hinted at by some), so I thought I should post. I would have preferred to do so as a comment, but I don’t have the reputation points.


回答 9

请注意,如果您的计算机上安装了多个版本的Python,则每个版本可能都有一些pip版本。

根据您的关联,您可能需要非常谨慎使用以下pip命令:

pip3 list 

在运行Python3.4的地方为我工作。简单使用pip list返回错误The program 'pip' is currently not installed. You can install it by typing: sudo apt-get install python-pip

Take note that if you have multiple versions of Python installed on your computer, you may have a few versions of pip associated with each.

Depending on your associations, you might need to be very cautious of what pip command you use:

pip3 list 

Worked for me, where I’m running Python3.4. Simply using pip list returned the error The program 'pip' is currently not installed. You can install it by typing: sudo apt-get install python-pip.


回答 10

正如@almenon指出的那样,这不再起作用,它也不是在代码中获取包信息的支持方式。以下引发异常:

import pip
installed_packages = dict([(package.project_name, package.version) 
                           for package in pip.get_installed_distributions()])

为此,您可以import pkg_resources。这是一个例子:

import pkg_resources
installed_packages = dict([(package.project_name, package.version)
                           for package in pkg_resources.working_set])

我上线了 v3.6.5

As @almenon pointed out, this no longer works and it is not the supported way to get package information in your code. The following raises an exception:

import pip
installed_packages = dict([(package.project_name, package.version) 
                           for package in pip.get_installed_distributions()])

To accomplish this, you can import pkg_resources. Here’s an example:

import pkg_resources
installed_packages = dict([(package.project_name, package.version)
                           for package in pkg_resources.working_set])

I’m on v3.6.5


回答 11

这是Fedora或其他rpm发行版的一线工具(基于@barraponto技巧):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

将此附加到上一个命令以获取更干净的输出:

 | sed -r 's:.*/(\w+)/__.*:\1:'

Here is the one-liner for fedora or other rpm distros (based on @barraponto tips):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

Append this to the previous command to get cleaner output:

 | sed -r 's:.*/(\w+)/__.*:\1:'

回答 12

获取site-packages/dist-packages/如果存在)所有文件/文件夹的名称,然后使用包管理器剥离通过软件包安装的文件/文件夹名称。

Get all file/folder names in site-packages/ (and dist-packages/ if it exists), and use your package manager to strip the ones that were installed via package.


回答 13

pip Frozen列出了所有已安装的软件包,即使不是通过pip / easy_install也是如此。在CentOs / Redhat上,找到了通过rpm安装的软件包。

pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.


回答 14

如果使用Anaconda python发行版,则可以使用以下conda list命令查看通过什么方法安装了什么:

user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0            py36h2fc01ae_0
alabaster                 0.7.10           py36h174008c_0
amqp                      2.2.2                     <pip>
anaconda                  5.1.0                    py36_2
anaconda-client           1.6.9                    py36_0

要获取安装者pip(可能包括pip其自身)安装的条目:

user@pc:~ $ conda list | grep \<pip
amqp                      2.2.2                     <pip>
astroid                   1.6.2                     <pip>
billiard                  3.5.0.3                   <pip>
blinker                   1.4                       <pip>
ez-setup                  0.9                       <pip>
feedgenerator             1.9                       <pip>

当然,您可能只想选择第一列即可进行处理(pip如果需要,则除外):

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp        
astroid
billiard
blinker
ez-setup
feedgenerator 

最后,您可以获取这些值并使用以下命令pip卸载所有这些值:

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y

请注意,使用-y标记pip uninstall来避免必须确认删除。

If you use the Anaconda python distribution, you can use the conda list command to see what was installed by what method:

user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0            py36h2fc01ae_0
alabaster                 0.7.10           py36h174008c_0
amqp                      2.2.2                     <pip>
anaconda                  5.1.0                    py36_2
anaconda-client           1.6.9                    py36_0

To grab the entries installed by pip (including possibly pip itself):

user@pc:~ $ conda list | grep \<pip
amqp                      2.2.2                     <pip>
astroid                   1.6.2                     <pip>
billiard                  3.5.0.3                   <pip>
blinker                   1.4                       <pip>
ez-setup                  0.9                       <pip>
feedgenerator             1.9                       <pip>

Of course you probably want to just select the first column, which you can do with (excluding pip if needed):

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp        
astroid
billiard
blinker
ez-setup
feedgenerator 

Finally you can grab these values and pip uninstall all of them using the following:

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y

Note the use of the -y flag for the pip uninstall to avoid having to give confirmation to delete.


回答 15

对于那些没有安装pip的人,我在github上找到了这个快速脚本(适用于Python 2.7.13):

import pkg_resources
distros = pkg_resources.AvailableDistributions()
for key in distros:
  print distros[key]

For those who don’t have pip installed, I found this quick script on github (works with Python 2.7.13):

import pkg_resources
distros = pkg_resources.AvailableDistributions()
for key in distros:
  print distros[key]

回答 16

点列表[选项]您可以在此处查看完整的参考

pip list [options] You can see the complete reference here


回答 17

至少对于Ubuntu(也许还有其他人)来说,这是可行的(受该线程中的上一篇文章的启发):

printf "Installed with pip:";
pip list 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo

At least for Ubuntu (maybe also others) works this (inspired by a previous post in this thread):

printf "Installed with pip:";
pip list 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo

pip安装失败,并显示“连接错误:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:598)”

问题:pip安装失败,并显示“连接错误:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:598)”

我是Python的新手,并尝试> pip install linkchecker在Windows 7上使用。

  • 无论软件包如何,pip安装都会失败。例如,> pip install scrapy还会导致SSL错误。
  • 原始安装的Python 3.4.1包含pip 1.5.6。我尝试做的第一件事是安装linkchecker。Python 2.7已经安装,它是ArcGIS附带的。python并且pip直到我安装3.4.1时才可从命令行使用。
  • > pip search linkchecker作品。可能是因为点子搜索无法验证站点的SSL证书。
  • 我在公司网络中,但是我们没有通过代理访问Internet。
  • 每台公司计算机(包括我的计算机)都具有受信任的根证书颁发机构,该证书颁发机构出于各种原因而被使用,包括启用对到https://google.com的 TLS流量的监视。不确定是否与此有关。

这是运行后我的pip.log的内容pip install linkchecker

Downloading/unpacking linkchecker
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Getting page https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ (Caused by <class 'http.client.CannotSendRequest'>: Request-sent)
  Will skip URL https://pypi.python.org/simple/ when looking for download links for linkchecker
  Cannot fetch index base URL https://pypi.python.org/simple/
  URLs to search for versions for linkchecker:
  * https://pypi.python.org/simple/linkchecker/
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Could not find any downloads that satisfy the requirement linkchecker
Cleaning up...
  Removing temporary dir C:\Users\jcook\AppData\Local\Temp\pip_build_jcook...
No distributions at all found for linkchecker
Exception information:
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "C:\Python34\lib\site-packages\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "C:\Python34\lib\site-packages\pip\req.py", line 1177, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "C:\Python34\lib\site-packages\pip\index.py", line 277, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for linkchecker

I am very new to Python and trying to > pip install linkchecker on Windows 7. Some notes:

  • pip install is failing no matter the package. For example, > pip install scrapy also results in the SSL error.
  • Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Python 2.7 was already installed, it came with ArcGIS. python and pip were not available from the command line until I installed 3.4.1.
  • > pip search linkchecker works. Perhaps that is because pip search does not verify the site’s SSL certificate.
  • I am in a company network but we do not go through a proxy to reach the Internet.
  • Each company computer (including mine) has a Trusted Root Certificate Authority that is used for various reasons including enabling monitoring TLS traffic to https://google.com. Not sure if that has anything to do with it.

Here are the contents of my pip.log after running pip install linkchecker:

Downloading/unpacking linkchecker
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Getting page https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ (Caused by <class 'http.client.CannotSendRequest'>: Request-sent)
  Will skip URL https://pypi.python.org/simple/ when looking for download links for linkchecker
  Cannot fetch index base URL https://pypi.python.org/simple/
  URLs to search for versions for linkchecker:
  * https://pypi.python.org/simple/linkchecker/
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Could not find any downloads that satisfy the requirement linkchecker
Cleaning up...
  Removing temporary dir C:\Users\jcook\AppData\Local\Temp\pip_build_jcook...
No distributions at all found for linkchecker
Exception information:
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "C:\Python34\lib\site-packages\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "C:\Python34\lib\site-packages\pip\req.py", line 1177, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "C:\Python34\lib\site-packages\pip\index.py", line 277, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for linkchecker

回答 0

—–> pip install gensim config –global http.sslVerify否

只需使用“ config –global http.sslVerify false”语句安装任何软件包

您可以通过将pypi.org和设置files.pythonhosted.org为受信任的主机来忽略SSL错误。

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package_name>

注意:在2018年4月的某个时候,Python软件包索引从迁移pypi.python.orgpypi.org。这意味着使用旧域的“受信任主机”命令不再起作用。

永久修复

自发布pip 10.0起,您应该能够通过pip自我升级永久解决此问题:

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org pip setuptools

或者通过重新安装以获得最新版本:

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

(…,然后get-pip.py与相关的Python解释器一起运行)。

pip install <otherpackage>应该在此之后工作。如果没有,那么您将需要做更多的事情,如下所述。


您可能需要将信任的主机和代理添加到配置文件中

pip.ini(Windows)或pip.conf(unix)

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

替代解决方案(安全程度较低)

大多数答案可能会带来安全问题。

帮助轻松安装大多数python软件包的两个解决方法是:

  • 使用easy_install:如果您确实很懒,不想浪费很多时间,请使用easy_install <package_name>。请注意,找不到某些软件包,或者会产生一些小错误。
  • 使用Wheel:下载python软件包Wheel并使用pip命令pip install wheel_package_name.whl安装该软件包。

—–> pip install gensim config –global http.sslVerify false

Just install any package with the “config –global http.sslVerify false” statement

You can ignore SSL errors by setting pypi.org and files.pythonhosted.org as trusted hosts.

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package_name>

Note: Sometime during April 2018, the Python Package Index was migrated from pypi.python.org to pypi.org. This means “trusted-host” commands using the old domain no longer work.

Permanent Fix

Since the release of pip 10.0, you should be able to fix this permanently just by upgrading pip itself:

$ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org pip setuptools

Or by just reinstalling it to get the latest version:

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

(… and then running get-pip.py with the relevant Python interpreter).

pip install <otherpackage> should just work after this. If not, then you will need to do more, as explained below.


You may want to add the trusted hosts and proxy to your config file.

pip.ini (Windows) or pip.conf (unix)

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

Alternate Solutions (Less secure)

Most of the answers could pose a security issue.

Two of the workarounds that help in installing most of the python packages with ease would be:

  • Using easy_install: if you are really lazy and don’t want to waste much time, use easy_install <package_name>. Note that some packages won’t be found or will give small errors.
  • Using Wheel: download the Wheel of the python package and use the pip command pip install wheel_package_name.whl to install the package.

回答 1

您可以使用以下参数指定证书:

pip --cert /etc/ssl/certs/FOO_Root_CA.pem install linkchecker

请参阅:文档»参考指南»点

如果指定您公司的根证书无效,则可能无法使用cURL:http : //curl.haxx.se/ca/cacert.pem

您必须使用PEM文件而不是CRT文件。如果您有CRT文件,则需要将该文件转换为PEM。注释中有报告说,该报告现在可用于CRT文件,但我尚未验证。

还要检查:SSL证书验证

You can specify a cert with this param:

pip --cert /etc/ssl/certs/FOO_Root_CA.pem install linkchecker

See: Docs » Reference Guide » pip

If specifying your company’s root cert doesn’t work maybe the cURL one will work: http://curl.haxx.se/ca/cacert.pem

You must use a PEM file and not a CRT file. If you have a CRT file you will need to convert the file to PEM There are reports in the comments that this now works with a CRT file but I have not verified.

Also check: SSL Cert Verification.


回答 2

kenorb的答案非常有用(而且很棒!)。
在他的解决方案中,也许这是最简单的解决方案: --trusted-host

例如,在这种情况下,您可以

pip install --trusted-host pypi.python.org linkchecker

不需要pem文件(或其他任何文件)。

kenorb’s answer is very useful (and great!).
Among his solutions, maybe this is the most simple one: --trusted-host

For example, in this case you can do

pip install --trusted-host pypi.python.org linkchecker

The pem file(or anything else) is unnecessary.


回答 3

对我来说,问题的解决,创建一个文件夹 pip,一个文件:pip.iniC:\Users\<username>\AppData\Roaming\ 例如:

C:\Users\<username>\AppData\Roaming\pip\pip.ini

我在里面写道:

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

我重新启动python,然后pip永久信任这些站点,并使用它们从中下载软件包。

如果在Windows上找不到AppData文件夹,请写入%appdata%文件资源管理器,它将出现。

For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users\<username>\AppData\Roaming\ e.g:

C:\Users\<username>\AppData\Roaming\pip\pip.ini

Inside it I wrote:

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

I restarted python, and then pip permanently trusted these sites, and used them to download packages from.

If you can’t find the AppData Folder on windows, write %appdata% in file explorer and it should appear.


回答 4

答案是非常相似的,并且有些令人困惑。就我而言,就是公司网络中的证书。我能够使用以下方法解决该问题:

pip install --trusted-host files.pythonhosted.org --trusted-host pypi.org --trusted-host pypi.python.org oauthlib -vvv

如这里所见。如果不需要详细的输出,则可以省略-vvv参数

The answers are quite similar and a bit confusing. In my case, the certificates in my company’s network was the issue. I was able to work around the problem using:

pip install --trusted-host files.pythonhosted.org --trusted-host pypi.org --trusted-host pypi.python.org oauthlib -vvv

As seen here. The -vvv argument can be omited if verbose output is not required


回答 5

永久修复

pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org

例如:

pip install <package name> --trusted-host pypi.org --trusted-host files.pythonhosted.org

Permanent Fix

pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org

For eg:

pip install <package name> --trusted-host pypi.org --trusted-host files.pythonhosted.org

回答 6

要一劳永逸地解决此问题,您可以验证您是否有pip.conf文件。

pip.conf根据文档,这是您应该在的位置:

在Unix上,默认配置文件是:$HOME/.config/pip/pip.conf尊重XDG_CONFIG_HOME环境变量。

在macOS上,配置文件是$HOME/Library/Application Support/pip/pip.conf目录是否$HOME/Library/Application Support/pip存在$HOME/.config/pip/pip.conf

在Windows上,配置文件为%APPDATA%\pip\pip.ini

在virtualenv内部:

在Unix和macOS上,文件为 $VIRTUAL_ENV/pip.conf

在Windows上,文件为: %VIRTUAL_ENV%\pip.ini

pip.conf应该看起来像:

[global]
trusted-host = pypi.python.org

pip install linkcheckerlinkchecker创建pip.conf文件后安装无投诉。

To solve this problem once and for all, you can verify that you have a pip.conf file.

This is where your pip.conf should be, according to the documentation:

On Unix the default configuration file is: $HOME/.config/pip/pip.conf which respects the XDG_CONFIG_HOME environment variable.

On macOS the configuration file is $HOME/Library/Application Support/pip/pip.conf if directory $HOME/Library/Application Support/pip exists else $HOME/.config/pip/pip.conf

On Windows the configuration file is %APPDATA%\pip\pip.ini.

Inside a virtualenv:

On Unix and macOS the file is $VIRTUAL_ENV/pip.conf

On Windows the file is: %VIRTUAL_ENV%\pip.ini

Your pip.conf should look like:

[global]
trusted-host = pypi.python.org

pip install linkchecker installed linkchecker without complains after I created the pip.conf file.


回答 7

我发现的最直接的方法是,从https://www.digicert.com/digicert-root-certificates.htm#roots从DigiCert下载和使用“ DigiCert高保证EV根CA”。

您可以通过单击地址栏中的锁定图标来访问https://pypi.python.org/以验证证书颁发者,或通过使用openssl来提高您的怪胎信誉:

$ openssl s_client -connect pypi.python.org:443
CONNECTED(00000003)
depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
verify error:num=20:unable to get local issuer certificate
verify return:0
---
Certificate chain
 0 s:/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro,/O=Python Software Foundation/CN=www.python.org
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA

证书链中的最后一个CN值是您需要下载的CA的名称。

要一次性完成,请执行以下操作:

  1. 从DigiCert 下载CRT
  2. 将CRT转换为PEM格式
  3. 将PIP_CERT环境变量导出到PEM文件的路径

(最后一行假设您正在使用bash shell)在运行pip之前。

curl -sO http://cacerts.digicert.com/DigiCertHighAssuranceEVRootCA.crt 
openssl x509 -inform DES -in DigiCertHighAssuranceEVRootCA.crt -out DigiCertHighAssuranceEVRootCA.pem -text
export PIP_CERT=`pwd`/DigiCertHighAssuranceEVRootCA.pem

为了使其可重复使用,请将DigiCertHighAssuranceEVRootCA.crt放在公共位置,然后在〜/ .bashrc中相应地导出PIP_CERT。

The most straightforward way I’ve found, is to download and use the “DigiCert High Assurance EV Root CA” from DigiCert at https://www.digicert.com/digicert-root-certificates.htm#roots

You can visit https://pypi.python.org/ to verify the cert issuer by clicking on the lock icon in the address bar, or increase your geek cred by using openssl:

$ openssl s_client -connect pypi.python.org:443
CONNECTED(00000003)
depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
verify error:num=20:unable to get local issuer certificate
verify return:0
---
Certificate chain
 0 s:/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro,/O=Python Software Foundation/CN=www.python.org
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA

The last CN value in the certificate chain is the name of the CA that you need to download.

For a one-off effort, do the following:

  1. Download the CRT from DigiCert
  2. Convert the CRT to PEM format
  3. Export the PIP_CERT environment variable to the path of the PEM file

(the last line assumes you are using the bash shell) before running pip.

curl -sO http://cacerts.digicert.com/DigiCertHighAssuranceEVRootCA.crt 
openssl x509 -inform DES -in DigiCertHighAssuranceEVRootCA.crt -out DigiCertHighAssuranceEVRootCA.pem -text
export PIP_CERT=`pwd`/DigiCertHighAssuranceEVRootCA.pem

To make this re-usable, put DigiCertHighAssuranceEVRootCA.crt somewhere common and export PIP_CERT accordingly in your ~/.bashrc.


回答 8

您可以通过以下方式解决问题CERTIFICATE_VERIFY_FAILED

  • 使用HTTP代替HTTPS(例如--index-url=http://pypi.python.org/simple/)。
  • 使用--cert <trusted.pem>CA_BUNDLE变量指定备用CA捆绑包。

    例如,您可以从Web浏览器转到失败的URL,然后将根证书导入到您的系统中。

  • 运行python -c "import ssl; print(ssl.get_default_verify_paths())"以检查当前的(验证是否存在)。

  • OpenSSL具有一对环境(SSL_CERT_DIRSSL_CERT_FILE),可用于指定不同的证书数据库PEP-476
  • 用于--trusted-host <hostname>将主机标记为可信。
  • 在Python中verify=False用于requests.get(请参阅:SSL证书验证)。
  • 使用--proxy <proxy>以避免证书检查。

有关更多信息,请参见套接字对象的TLS / SSL包装器-验证证书

You’ve the following possibilities to solve issue with CERTIFICATE_VERIFY_FAILED:

  • Use HTTP instead of HTTPS (e.g. --index-url=http://pypi.python.org/simple/).
  • Use --cert <trusted.pem> or CA_BUNDLE variable to specify alternative CA bundle.

    E.g. you can go to failing URL from web-browser and import root certificate into your system.

  • Run python -c "import ssl; print(ssl.get_default_verify_paths())" to check the current one (validate if exists).

  • OpenSSL has a pair of environments (SSL_CERT_DIR, SSL_CERT_FILE) which can be used to specify different certificate databasePEP-476.
  • Use --trusted-host <hostname> to mark the host as trusted.
  • In Python use verify=False for requests.get (see: SSL Cert Verification).
  • Use --proxy <proxy> to avoid certificate checks.

Read more at: TLS/SSL wrapper for socket objects – Verifying certificates.


回答 9

正确设置时间和日期!

对我来说,结果表明我的日期和时间在Raspberry Pi上配置错误。结果是使用https://files.pythonhosted.org/服务器,所有SSL和HTTPS连接均失败。

像这样更新它:

sudo date -s "Wed Thu  23 11:12:00 GMT+1 2018"
sudo dpkg-reconfigure tzdata

或直接以Google的时间为准:

参考:https : //superuser.com/a/635024/935136

sudo date -s "$(curl -s --head http://google.com | grep ^Date: | sed 's/Date: //g')"
sudo dpkg-reconfigure tzdata

Set Time and Date correct!

For me, it came out that my date and time was misconfigured on Raspberry Pi. The result was that all SSL and HTTPS connections failed, using the https://files.pythonhosted.org/ server.

Update it like this:

sudo date -s "Wed Thu  23 11:12:00 GMT+1 2018"
sudo dpkg-reconfigure tzdata

Or directly with e.g. Google’s time:

Ref.: https://superuser.com/a/635024/935136

sudo date -s "$(curl -s --head http://google.com | grep ^Date: | sed 's/Date: //g')"
sudo dpkg-reconfigure tzdata

回答 10

我最近遇到了这个问题,因为我公司的Web内容过滤器使用自己的证书颁发机构,以便可以过滤SSL流量。在我的情况下,PIP似乎没有使用系统的CA证书,从而产生了您提到的错误。后来将PIP降级到1.2.1版会带来一系列问题,因此我回到了Python 3.4附带的原始版本。

我的解决方法非常简单:使用easy_install。它要么不检查证书(例如旧的PIP版本),要么知道使用系统证书,因为它每次都对我有用,我仍然可以使用PIP卸载使用easy_install安装的软件包。

如果那行不通,并且您可以访问没有问题的网络或计算机,则可以始终设置自己的个人PyPI服务器:如何在没有镜像的情况下创建本地自己的pypi存储库索引?

我几乎做到了,直到我尝试将其easy_install作为最后的努力。

I recently ran into this problem because of my company’s web content filter that uses its own Certificate Authority so that it can filter SSL traffic. PIP doesn’t seem to be using the system’s CA certificates in my case, producing the error you mention. Downgrading PIP to version 1.2.1 presented its own set of problems later on, so I went back to the original version that came with Python 3.4.

My workaround is quite simple: use easy_install. Either it doesn’t check the certs (like the old PIP version), or it knows to use the system certs because it works every time for me and I can still use PIP to uninstall packages installed with easy_install.

If that doesn’t work and you can get access to a network or computer that doesn’t have the issue, you could always setup your own personal PyPI server: how to create local own pypi repository index without mirror?

I almost did that until I tried using easy_install as a last ditch effort.


回答 11

您可以尝试使用http而不是https来绕过SSL错误。当然,就安全性而言,并不是最佳选择,但是如果您急于使用它,可以采取以下措施:

pip install --index-url=http://pypi.python.org/simple/ linkchecker

You can try to bypass the SSL error by using http instead of https. Of course this is not optimal in terms of security, but if you are in a hurry it should do the trick:

pip install --index-url=http://pypi.python.org/simple/ linkchecker

回答 12

使用答案

pip install --trusted-host pypi.python.org <package>

工作。但是,您必须检查是否存在重定向或缓存pip命中。在Windows 7上pip 9.0.1,我必须运行

pip install \
  --trusted-host pypi.python.org \
  --trusted-host pypi.org \
  --trusted-host files.pythonhosted.org \
  <package>

您可以使用详细标志找到它们。

The answers to use

pip install --trusted-host pypi.python.org <package>

work. But you’ll have to check if there are redirects or caches pip is hitting. On Windows 7 with pip 9.0.1, I had to run

pip install \
  --trusted-host pypi.python.org \
  --trusted-host pypi.org \
  --trusted-host files.pythonhosted.org \
  <package>

You can find these with the verbose flag.


回答 13

我使用easy_install安装了pip 1.2.1,并升级到了最新版本的pip(当时为6.0.7),可以在我的情况下安装软件包。

easy_install pip==1.2.1
pip install --upgrade pip

I installed pip 1.2.1 with easy_install and upgraded to latest version of pip (6.0.7 at the time) which is able to install packages in my case.

easy_install pip==1.2.1
pip install --upgrade pip

回答 14

您有4个选择:

使用证书作为参数

$ pip install --cert /path/to/mycertificate.crt linkchecker

在证书中使用证书 pip.conf

创建此文件:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

并添加以下行:

[global]
cert = /path/to/mycertificate.crt

忽略证书并使用HTTP

$ pip install --trusted-host pypi.python.org linkchecker

忽略证书并在pip.conf中使用HTTP

创建此文件:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

并添加以下行:

[global]
trusted-host = pypi.python.org

资源

You have 4 options:

Using a certificate as parameter

$ pip install --cert /path/to/mycertificate.crt linkchecker

Using a certificate in a pip.conf

Create this file:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

and add these lines:

[global]
cert = /path/to/mycertificate.crt

Ignoring certificate and using HTTP

$ pip install --trusted-host pypi.python.org linkchecker

Ignoring certificate and using HTTP in a pip.conf

Create this file:

$HOME/.pip/pip.conf (Linux)

%HOME%\pip\pip.ini (Windows)

and add these lines:

[global]
trusted-host = pypi.python.org

Source


回答 15

首先,

    pip install --trusted-host pypi.python.org <package name>

没有为我工作。我一直收到CERTIFICATE_VERIFY_FAILED错误。但是,我在错误消息中注意到它们引用了“ pypi.org”站点。因此,我将其用作受信任的主机名,而不是pypi.python.org。那几乎使我到了那里。CERTIFICATE_VERIFY_FAILED仍使加载失败,但是稍后。找到对失败网站的引用,我将其作为受信任的主机。最终对我有用的是:

    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package name>

First of all,

    pip install --trusted-host pypi.python.org <package name>

did not work for me. I kept getting the CERTIFICATE_VERIFY_FAILED error. However, I noticed in the error messages that they referenced the ‘pypi.org’ site. So, I used this as the trusted host name instead of pypi.python.org. That almost got me there; the load was still failing with CERTIFICATE_VERIFY_FAILED, but at a later point. Finding the reference to the website that was failing, I included it as a trusted host. What eventually worked for me was:

    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package name>

回答 16

我不确定这是否相关,但是我有一个类似的问题,可以通过将这些文件从Anaconda3 / Library / bin复制到Anaconda3 / DLLs来解决:

libcrypto-1_1-x64.dll

libssl-1_1-x64.dll

I’m not sure if this is related, but I had a similar problem which was fixed by copying these files from Anaconda3/Library/bin to Anaconda3/DLLs :

libcrypto-1_1-x64.dll

libssl-1_1-x64.dll


回答 17

pip install ftputil在64位Windows 7 Enterprise上尝试使用ActivePython 2.7.8,ActivePython 3.4.1和“常规” Python 3.4.2时遇到了相同的问题。所有尝试均以与OP相同的错误失败。

通过降级为pip 1.2.1解决了Python 3.4.2的问题:(easy_install pip==1.2.1请参阅https://stackoverflow.com/a/16370731/234235)。同样的修复也适用于ActivePython 2.7.8。

该bug于2013年3月报告,目前仍在打开:https : //github.com/pypa/pip/issues/829

Had the same problem trying pip install ftputil with ActivePython 2.7.8, ActivePython 3.4.1, and “stock” Python 3.4.2 on 64-bit Windows 7 Enterprise. All attempts failed with the same errors as OP.

Worked around the problem for Python 3.4.2 by downgrading to pip 1.2.1: easy_install pip==1.2.1 (see https://stackoverflow.com/a/16370731/234235). Same fix also worked for ActivePython 2.7.8.

The bug, reported in March 2013, is still open: https://github.com/pypa/pip/issues/829.


回答 18

直到我使用–verbose选项查看它想要进入files.pythonhosted.org而不是pypi.python.org为止,此页面上的所有内容都对我没有作用:

pip install --trusted-host files.pythonhosted.org <package_name>

因此,请通过–verbose选项检查实际失败的URL。

Nothing on this page worked for me until I used the –verbose option to see that it wanted to get to files.pythonhosted.org rather than pypi.python.org:

pip install --trusted-host files.pythonhosted.org <package_name>

So check the URL that it’s actually failing on via the –verbose option.


回答 19

我通过删除我的点子并安装了较旧版本的点子来解决此问题:https : //pypi.python.org/pypi/pip/1.2.1

I solved this problem by removing my pip and installing the older version of pip: https://pypi.python.org/pypi/pip/1.2.1


回答 20

您可以尝试忽略“ https”:

pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org  [your package..]

You can try this to ignore “https”:

pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org  [your package..]

回答 21

一种解决方案(对于Windows)是pip.ini%AppData%\pip\文件夹上创建一个名为的文件(如果该文件夹不存在,则创建该文件夹)并插入以下详细信息:

[global]
cert = C:/certs/python_root.pem
proxy = http://my_user@my_company.com:my_password@proxy_ip:proxy_port

…然后我们可以执行安装指令:

pip3 install PyQt5

另一个选择是使用代理和证书的参数来安装软件包。

$ pip3 install --proxy http://my_user@my_company.com:my_password@proxy_ip:proxy_port \
   --cert C:/certs/python_root.pem PyQt5

要将证书*.cer文件转换为所需*.pem格式,请执行以下指令:

$ openssl x509 -inform der -in python_root.cer -out python_root.pem

希望这对某人有帮助!

One solution (for Windows) is to create a file called pip.ini on the %AppData%\pip\ folder (create the folder if it doesn’t exist) and insert the following details:

[global]
cert = C:/certs/python_root.pem
proxy = http://my_user@my_company.com:my_password@proxy_ip:proxy_port

…and then we can execute the install instruction:

pip3 install PyQt5

Another option is to install the package using arguments for the proxy and certificate…

$ pip3 install --proxy http://my_user@my_company.com:my_password@proxy_ip:proxy_port \
   --cert C:/certs/python_root.pem PyQt5

To convert the certificate *.cer files to the required *.pem format execute the following instruction:

$ openssl x509 -inform der -in python_root.cer -out python_root.pem

Hope this helps someone!


回答 22

就我而言,这是由于SSL证书是由公司内部CA签署的。使用类似的解决方法pip --cert无济于事,但以下软件包提供了帮助:

pip install pip_system_certs

参见:https : //pypi.org/project/pip-system-certs/

该软件包修补pip并在运行时请求使用默认系统存储中的证书(而不是捆绑的证书ca)。

这将使pip可以验证与cert的服务器之间的tls / ssl连接是否受系统安装信任。

In my case it was due to SSL certificate being signed by internal CA of my company. Using workarounds like pip --cert did not help, but the following package did:

pip install pip_system_certs

See: https://pypi.org/project/pip-system-certs/

This package patches pip and requests at runtime to use certificates from the default system store (rather than the bundled certs ca).

This will allow pip to verify tls/ssl connections to servers who’s cert is trusted by your system install.


回答 23

对我来说,这是因为以前我正在运行将代理(设置为提琴手),重新打开控制台或重新启动的脚本,以解决此问题。

for me this is because previously I’m running script which set proxy (to fiddler), reopening console or reboot fix the problem.


回答 24

最近,我在Visual Studio 2015的python 3.6中遇到了同样的问题。花了2天后,我得到了解决方案及其对我来说很好的工作。

尝试使用pip或从Visual Studio安装numpy时出现以下错误收集numpy无法获取URL https://pypi.python.org/simple/numpy/:确认ssl证书时出现问题:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:748)-跳过找不到满足numpy要求的版本(来自版本:)找不到numpy的匹配发行版

解析度 :

对于Windows操作系统

  1. 打开->“%appdata%”如果不存在,则创建“ pip”文件夹。
  2. 在pip文件夹中创建“ pip.ini”文件。
  3. 编辑文件并编写
    [global]
    trusted-host = pypi.python.org保存并关闭文件。现在使用pip / visual studio安装,效果很好。

Recently I faced the same issue in python 3.6 with visual studio 2015. After spending 2 days, I got the solution and its working fine for me.

I got below error while try to install numpy using pip or from visual studio Collecting numpy Could not fetch URL https://pypi.python.org/simple/numpy/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748) – skipping Could not find a version that satisfies the requirement numpy (from versions: ) No matching distribution found for numpy

Resolution :

For Windows OS

  1. open -> “%appdata%” Create “pip” folder if not exists.
  2. In pip folder create “pip.ini” file.
  3. Edit file and write
    [global]
    trusted-host = pypi.python.org Save and Close the file. Now install using pip/visual studio it works fine.

回答 25

就我而言,我在最小的高山码头工人镜像中运行Python。它缺少根CA证书。固定:

apk update && apk add ca-certificates

In my case, I was running Python in the minimal alpine docker image. It was missing root CA certificates. Fix:

apk update && apk add ca-certificates


回答 26

瓦尔斯坦回答帮助了我。

我在电脑上的任何地方都找不到pip.ini文件。以下内容也是如此。

  1. 转到AppData文件夹。您可以通过打开命令提示符并键入echo%AppData%来获取appdata文件夹。

使用命令提示的AppData位置

或者直接在Windows资源管理器中键入%AppData%。

Windows资源管理器中AppData的位置

  1. 在该appdata文件夹内创建一个名为pip的文件夹。

  2. 在您刚创建的pip文件夹中,创建一个名为pip.ini的简单文本文件。

  3. 使用您选择的简单编辑器将以下配置设置粘贴到该文件中。

pip.ini文件:

[list]
format=columns

[global]
trusted-host = pypi.python.org pypi.org

您现在应该可以进行了。

Vaulstein answer helped me.

I did not find the pip.ini file anywhere on my pc. So did the following.

  1. Went to the the AppData folder. You can get the appdata folder by opening up the command prompt and type echo %AppData%

AppData location using command prompt

Or simply type %AppData% in windows explorer.

AppData location in windows explorer

  1. Create a folder called pip inside of that appdata folder.

  2. In that pip folder that you just created, create a simple textfile called pip.ini

  3. Past the following config settings in that file using a simple editor of your choice.

pip.ini file:

[list]
format=columns

[global]
trusted-host = pypi.python.org pypi.org

You should now be good to go.


回答 27

我遇到了类似的问题。对我有用的解决方案1)卸载python 2.7 2)删除python27文件夹3)重新安装最新的python

I faced a similar issue. The solution that worked for me 1) uninstall python 2.7 2) delete python27 folder 3) reinstall the latest python


回答 28

对我而言,建议的方法都无效-使用cert,HTTP,可信主机。

在我的情况下,切换到该程序包的另一个版本是可行的(在此实例中,paho-mqtt 1.3.1代替了paho-mqtt 1.3.0)。

看起来问题是特定于该软件包版本的。

For me none of the suggested methods worked – using cert, HTTP, trusted-host.

In my case switching to a different version of the package worked (paho-mqtt 1.3.1 instead of paho-mqtt 1.3.0 in this instance).

Looks like problem was specific to that package version.


回答 29

如果您的系统中缺少某些证书,则可能会出现此问题。例如,在opensuse上安装ca-certificates-mozilla

You may have this problem if some certificates are missing in your system.eg on opensuse install ca-certificates-mozilla