标签归档:pip

如何在macOS或OS X上安装pip?

问题:如何在macOS或OS X上安装pip?

昨天我大部分时间都在寻找安装的明确答案pip(Python的软件包管理器)。我找不到一个好的解决方案。

如何安装?

I spent most of the day yesterday searching for a clear answer for installing pip (package manager for Python). I can’t find a good solution.

How do I install it?


回答 0

更新(2019年1月):

easy_install弃用。请get-pip.py改用:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

旧答案:

easy_install pip

如果您需要管理员权限才能运行此程序,请尝试:

sudo easy_install pip

UPDATE (Jan 2019):

easy_install has been deprecated. Please use get-pip.py instead:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Old answer:

easy_install pip

If you need admin privileges to run this, try:

sudo easy_install pip

回答 1

⚡️ TL; DR -一个线的解决方案。

您要做的就是:

sudo easy_install pip

2019:⚠️ easy_install已被弃用。检查下面的方法2以进行首选安装!

我做了一个gif,因为。为什么不?

细节:

⚡️好,我读了上面给出的解决方案,但这是一个易于安装的解决方案pip

MacOS Python已安装。但是要确保已Python安装,请打开终端并运行以下命令。

python --version

如果此命令返回的版本号表示Python存在。这也意味着您已经可以easy_install考虑使用macOS/OSX

Now️现在,您所要做的就是运行以下命令。

sudo easy_install pip

之后,pip将被安装,您将可以使用它来安装其他软件包。

如果您以pip这种方式安装有任何问题,请告诉我。

干杯!

PS我最终在博客上写了一篇有关它的文章。快速提示:如何在macOS或OS X上安装pip?


更新(2019年1月):方法2:两线解决方案-

easy_install弃用。请get-pip.py改用。

首先下载get-pip文件

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

现在运行此文件进行安装 pip

python get-pip.py

那应该做。

你说的另一个gif?来呀!

⚡️ TL;DR — One line solution.

All you have to do is:

sudo easy_install pip

2019: ⚠️easy_install has been deprecated. Check Method #2 below for preferred installation!

I made a gif, coz. why not?

Details:

⚡️ OK, I read the solutions given above, but here’s an EASY solution to install pip.

MacOS comes with Python installed. But to make sure that you have Python installed open the terminal and run the following command.

python --version

If this command returns a version number that means Python exists. Which also means that you already have access to easy_install considering you are using macOS/OSX.

ℹ️ Now, all you have to do is run the following command.

sudo easy_install pip

After that, pip will be installed and you’ll be able to use it for installing other packages.

Let me know if you have any problems installing pip this way.

Cheers!

P.S. I ended up blogging a post about it. QuickTip: How Do I Install pip on macOS or OS X?


UPDATE (Jan 2019): METHOD #2: Two line solution —

easy_install has been deprecated. Please use get-pip.py instead.

First of all download the get-pip file

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Now run this file to install pip

python get-pip.py

That should do it.

Another gif you said? Here ya go!


回答 2

您可以在OS X上通过Homebrew安装它。为什么要在Homebrew中安装Python?

OS X附带的Python版本非常适合学习,但不利于开发。OS X附带的版本可能已从官方的当前Python发行版过时了,该版本被认为是稳定的生产版本。(来源

Homebrew是OS X的软件包管理器。在Homebrew页面上找到更多详细信息。一旦安装了Homebrew,请运行以下命令以安装最新的Python,Pip和Setuptools:

brew install python

You can install it through Homebrew on OS X. Why would you install Python with Homebrew?

The version of Python that ships with OS X is great for learning but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. (source)

Homebrew is something of a package manager for OS X. Find more details on the Homebrew page. Once Homebrew is installed, run the following to install the latest Python, Pip & Setuptools:

brew install python

回答 3

我很惊讶没有人提到这一点-自2013年以来,python本身就可以安装pip,不需要外部命令(也不需要Internet连接)。

sudo -H python -m ensurepip

这将创建与安装类似的安装easy_install

I’m surprised no-one has mentioned this – since 2013, python itself is capable of installing pip, no external commands (and no internet connection) required.

sudo -H python -m ensurepip

This will create a similar install to what easy_install would.


回答 4

在Mac上:

  1. 安装easy_install

    curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python
  2. 安装点子

    sudo easy_install pip
  3. 现在,您可以安装外部模块。例如

    pip install regex   # This is only an example for installing other modules

On Mac:

  1. Install easy_install

    curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python
    
  2. Install pip

    sudo easy_install pip
    
  3. Now, you could install external modules. For example

    pip install regex   # This is only an example for installing other modules
    

回答 5

pip可通过OS X在OS X上使用easy_install
打开一个终端并输入:

sudo easy_install pip

当提示您输入密码时,输入您的常规登录密码。
安装完成后,您应该可以pip按预期使用。

注意:这也适用于其他python包

pip is available on OS X via easy_install.
Open a terminal and type:

sudo easy_install pip

When prompted for a password enter your normal login password.
After the installation has completed you should be able to use pip as expected.

note: this works for other python packages too


回答 6

2019年10月更新:MacOs Mojave

MacOS附带python2,但不附带pip。无论如何,最好使用自制软件进行管理,您必须在安装之前进行安装:

https://docs.brew.sh/安装

安装python2:

brew install python

警告:对于现代macOS(2019),可以安装python3,并且python2您确实需要执行以下操作:brew install python@2

安装python3:

brew install python3

更新:Python 3

如果您安装python3,则会自动安装pip。

brew install python3

新2019:现在使用pip版本3,请使用pip3或您可以执行:python3使用版本3.当您使用pip3安装软件包时,它们将与分开python2

老:您只需要升级pip,但在此之前,您需要创建一个虚拟环境以使用Python3。您可以使用项目文件夹或任何文件夹:

python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip

检查版本:

pip -V
python --version

NEW 2019:
pip3 -V
python3 --version

要停用环境:

$ deactivate

UPDATED 2019 October: MacOs Mojave

MacOS comes with python2, but not with pip. Anyway, it’s better to manage it with homebrew, you must install it before:

https://docs.brew.sh/Installation

Install python2:

brew install python

WARNING: for a modern macOS (2019) this can install python3, and for python2 you really need to do: brew install python@2

Install python3:

brew install python3

UPDATE: Python 3

If you install python3, pip will be installed automatically.

brew install python3

NEW 2019: now to use pip version 3, use pip3 , or you can execute: python3, to use version 3. When you install packages with pip3 they will be separated from python2.

OLD: You need only to upgrade pip, but before that you need create a virtual environment to work with Python 3. You can use a project folder or any folder:

python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip

Check the versions:

pip -V
python --version

NEW 2019:
pip3 -V
python3 --version

To deactivate the environment:

$ deactivate

回答 7

最简单的解决方案是按照pip主页上安装说明进行操作

基本上,这包括:

  • 下载get-pip.py。确保通过遵循受信任的链接来执行此操作,因为您将必须以root用户身份运行脚本。
  • 呼叫 sudo python get-pip.py

该解决方案的主要优点是,它会为曾经运行过的python版本安装pip get-pip.py,这意味着,如果使用默认的OS X python安装来运行get-pip.py,则将从系统中为python安装安装pip。

大多数在OS X上使用软件包管理器(自制或Macport)的解决方案都会在软件包管理器的环境中创建python的冗余安装,这可能会在您的系统中造成不一致,因为根据您所执行的操作,您可以将安装称为python,而不是另一个。

The simplest solution is to follow the installation instruction from pip’s home site.

Basically, this consists in:

  • downloading get-pip.py. Be sure to do this by following a trusted link since you will have to run the script as root.
  • call sudo python get-pip.py

The main advantage of that solution is that it install pip for the python version that has been used to run get-pip.py, which means that if you use the default OS X installation of python to run get-pip.py you will install pip for the python install from the system.

Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.


回答 8

尽管Python已随MacOS一起提供,但安装单独的Python副本是一种普遍的选择。您有责任确保使用的是您打算使用的Python副本。但是,这样做的好处是拥有最新的Python版本,并且在出现严重错误的情况下可以防止系统崩溃。

要使用HomeBrew安装Python :

brew update
brew install python # or brew install python3

现在确认我们正在使用新安装的Python:

ls -lh `which python`

…应显示指向其中带有“地窖”的路径的符号链接,例如:

lrwxr-xr-x  1 chris  admin    35B Dec  2 13:40 /usr/local/bin/python -> ../Cellar/python/2.7.8_2/bin/python

Pip应该与Python一起安装。您可能需要输入以下内容来升级它:

pip install --upgrade pip

现在,您可以在PyPI上安装任何50,000+个软件包。

其他注意事项

以前,我使用get-pip.py安装pip。但是,文档警告说,get-pip.py与软件包管理器不协调,可能会使您的系统处于不一致状态。无论如何,没有必要,因为从2.7.9开始,Python现在已包含 pip 。

请注意,pip不是Python的唯一软件包管理器。还有easy_install。将两者混合使用是不好的,所以不要这样做。

最后,如果您同时安装了Python 2和3,pip将指向最后安装的Python。养成显式使用pip2pip3的习惯,因此您可以确定哪个Python正在获取新库。

骇客入侵!

Installing a separate copy of Python is a popular option, even though Python already comes with MacOS. You take on the responsibility to make sure you’re using the copy of Python you intend. But, the benefits are having the latest Python release and some protection from hosing your system if things go badly wrong.

To install Python using HomeBrew:

brew update
brew install python # or brew install python3

Now confirm that we’re working with our newly installed Python:

ls -lh `which python`

…should show a symbolic link to a path with “Cellar” in it like:

lrwxr-xr-x  1 chris  admin    35B Dec  2 13:40 /usr/local/bin/python -> ../Cellar/python/2.7.8_2/bin/python

Pip should be installed along with Python. You might want to upgrade it by typing:

pip install --upgrade pip

Now you’re ready to install any of the 50,000+ packages on PyPI.

Other Notes

Formerly, I’ve used get-pip.py to install pip. But, the docs warn that get-pip.py does not coordinate with package managers and may leave your system in an inconsistent state. Anyway, there’s no need, given that pip is now included with Python as of 2.7.9.

Note that pip isn’t the only package manager for Python. There’s also easy_install. It’s no good to mix the two, so don’t do it.

Finally, if you have both Python 2 and 3 installed, pip will point to whichever Python you installed last. Get in the habit of explicitly using either pip2 or pip3, so you’re sure which Python is getting the new library.

Happy hacking!


回答 9

对于同时安装了python2和python3的用户,以下是解决方案:

python2.7 -m ensurepip --default-pip

另外,如果您想为python3.6安装pip:

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

For those who have both python2 & python3 installed, here’s the solution:

python2.7 -m ensurepip --default-pip

Additionally, if you wanna install pip for python3.6:

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

回答 10

在最新版本(我相信至少从塞拉利昂起,从优胜美地或El Capitan起),如果您使用自制软件brew postinstall python3brew install python3则需要运行。

所以,

brew install python3 # this only installs python
brew postinstall python3 # this installs pip

更新-1.5之后的自制软件版本

根据官方的Homebrew页面

在2018年3月1日,python公式将升级到Python 3.x,并且将添加python @ 2公式以安装Python 2.7(尽管这仅是小桶,因此默认情况下,不将python和python2添加到PATH中,而无需手动冲泡链接–force)。我们将维护python2,python3和python @ 3别名。

因此,要安装Python 3,请运行以下命令:

brew install python3

然后,pip会自动安装,您可以通过来安装任何软件包pip install <package>

On the recent version (from Yosemite or El Capitan I believe… at least from Sierra onward), you need to run brew postinstall python3 after brew install python3 if you use homebrew.

So,

brew install python3 # this only installs python
brew postinstall python3 # this installs pip

UPDATED – Homebrew version after 1.5

According to the official Homebrew page:

On 1st March 2018 the python formula will be upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7 (although this will be keg-only so neither python nor python2 will be added to the PATH by default without a manual brew link –force). We will maintain python2, python3 and python@3 aliases.

So to install Python 3, run the following command:

brew install python3

Then, the pip is installed automatically, and you can install any package by pip install <package>.


回答 11

下载此文件:get-pip.py

然后只需键入

sudo python get-pip.py

确保您与get-pip.py位于同一目录中,或者为该文件提供正确的路径。

有关详细信息,您可以访问:http : //pip.readthedocs.org/en/latest/installing.html

或者,http://thegauraw-blog-blog.tumblr.com/post/47601704154/how-to-install-pip-in-both-windows-ubuntu-easiest-way

Download this file: get-pip.py

Then simply type

sudo python get-pip.py

Make sure you are on the same directory as get-pip.py or you supply the correct path for that file.

For details, you can visit: http://pip.readthedocs.org/en/latest/installing.html

or, http://thegauraw-blog-blog.tumblr.com/post/47601704154/how-to-install-pip-in-both-windows-ubuntu-easiest-way


回答 12

您应该先安装Brew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

然后brew安装Python

brew install python

然后pip会工作

You should install Brew first:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then brew install Python

brew install python

Then pip will work


回答 13

如果要“ pip3”,可以执行以下操作:

通过酿造: brew install python3

然后你可以执行

pip3 <command> [options]

If you want “pip3” you can do the ff:

via brew: brew install python3

then you can execute

pip3 <command> [options]


回答 14

$ sudo port install py27-pip

然后更新您的PATH以包含py27-pip bin目录(您可以将其添加到〜/ .bash_profile PATH = / opt / local / Library / Frameworks / Python.framework / Versions / 2.7 / bin:$ PATH中)

点子将在新的终端窗口中可用。

$ sudo port install py27-pip

Then update your PATH to include py27-pip bin directory (you can add this in ~/.bash_profile PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH

pip will be available in new terminal window.


回答 15

要安装或升级piphttp://www.pip-installer.org/en/latest/installing.html下载get-pip.py

然后运行以下命令: sudo python get-pip.py

例如:

sudo python Desktop/get-pip.py 
Password:
  Downloading/unpacking pip
  Downloading pip-1.5.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Successfully installed pip
Cleaning up...

sudo pip install pymongo
Password:
Downloading/unpacking pymongo
  Downloading pymongo-2.6.3.tar.gz (324kB): 324kB downloaded
  Running setup.py (path:/private/var/folders/0c/jb79t3bx7cz6h7p71ydhwb_m0000gn/T/pip_build_goker/pymongo/setup.py) egg_info for package pymongo

Installing collected packages: pymongo
...

To install or upgrade pip, download get-pip.py from http://www.pip-installer.org/en/latest/installing.html

Then run the following: sudo python get-pip.py

For example:

sudo python Desktop/get-pip.py 
Password:
  Downloading/unpacking pip
  Downloading pip-1.5.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Successfully installed pip
Cleaning up...

sudo pip install pymongo
Password:
Downloading/unpacking pymongo
  Downloading pymongo-2.6.3.tar.gz (324kB): 324kB downloaded
  Running setup.py (path:/private/var/folders/0c/jb79t3bx7cz6h7p71ydhwb_m0000gn/T/pip_build_goker/pymongo/setup.py) egg_info for package pymongo

Installing collected packages: pymongo
...

回答 16

无需安装 sudo

如果您想要安装pip而不需要sudo,那么在尝试全局安装软件包时总是会感到沮丧,请像这样pip在本地文件夹中安装/usr/local

curl https://bootstrap.pypa.io/get-pip.py > get-pip.py
python get-pip.py --prefix=/usr/local/

然后:

pip install <package-of-choice> 没有 sudo

Install without the need for sudo

If you want to install pip without the need for sudo, which is always frustrating when trying to install packages globally, install pip in your local folder /usr/local like this:

curl https://bootstrap.pypa.io/get-pip.py > get-pip.py
python get-pip.py --prefix=/usr/local/

and then:

pip install <package-of-choice> without sudo


回答 17

首先安装python3,然后使用pip3安装软件包。

brew install python

将会安装python3,并且pip附带了它。要使用pip安装一些软件包,请运行以下命令

pip3 install package

注意它是pip3,因为您想使用python3。

Install python3 first, then use pip3 to install packages.

brew install python

python3 will be installed, and pip is shipped with it. To use pip to install some package, run the following

pip3 install package

Notice it’s pip3 because you want to use python3.


回答 18

从以下网站下载python设置工具:

https://pypi.python.org/pypi/setuptools

使用tar文件。

下载后,转到下载的文件夹并运行

python setup.py install

完成后,您将拥有easy_install。

请使用以下内容安装pip:

sudo easy_install pip

Download python setup tools from the below website:

https://pypi.python.org/pypi/setuptools

Use the tar file.

Once you download, go to the downloaded folder and run

python setup.py install

Once you do that,you will have easy_install.

Use the below then to install pip:

sudo easy_install pip

回答 19

以某种方式无法轻松安装在我的旧Mac(10.8)上不起作用。这解决了我的问题。

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

如果没有wget,只需在浏览器中打开,https://bootstrap.pypa.io/get-pip.py然后另存为get-pip.py

Somehow easy install doesn’t work on my old mac (10.8). This solve my problem.

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

If you do not have wget, just open in browser https://bootstrap.pypa.io/get-pip.py then save as get-pip.py


回答 20

我向您推荐水蟒。它是由Python支持的领先的开放数据科学平台。安装了许多基本软件包。Anaconda(conda)附带了它自己的安装pip

I recommend Anaconda to you. It’s the leading open data science platform powered by Python. There are many basic packages installed. Anaconda (conda) comes with its own installation of pip.


使用pip安装特定的软件包版本

问题:使用pip安装特定的软件包版本

我正在尝试使用通过该--no-site-packages选项创建的新virtualenv安装MySQL_python适配器的1.2.2版本。PyPi中显示的当前版本是1.2.3。有没有办法安装旧版本?我发现有一篇文章指出应该这样做:

pip install MySQL_python==1.2.2

但是,安装后,它仍显示MySQL_python-1.2.3-py2.6.egg-info在站点包中。这是此软件包专用的问题,还是我做错了什么?

I’m trying to install version 1.2.2 of the MySQL_python adaptor, using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I found an article stating that this should do it:

pip install MySQL_python==1.2.2

When installed, however, it still shows MySQL_python-1.2.3-py2.6.egg-info in the site packages. Is this a problem specific to this package, or am I doing something wrong?


回答 0

TL; DR:

  • pip install -Iv(即pip install -Iv MySQL_python==1.2.2

首先,我发现您要执行的操作有两个问题。由于您已经安装了版本,因此应该卸载当前的现有驱动程序或使用pip install -I MySQL_python==1.2.2

但是,您很快就会发现这不起作用。如果您查看pip的安装日志,或者执行pip的安装日志,pip install -Iv MySQL_python==1.2.2则会发现PyPI URL链接不适用于MySQL_python v1.2.2。您可以在这里验证:http : //pypi.python.org/pypi/MySQL-python/1.2.2

由于sourceforge.net的最新升级和PyPI的过时URL,下载链接404s和后备URL链接正在无限重定向。

因此,要正确安装驱动程序,可以按照以下步骤操作:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

TL;DR:

  • pip install -Iv (i.e. pip install -Iv MySQL_python==1.2.2)

First, I see two issues with what you’re trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2

However, you’ll soon find out that this doesn’t work. If you look at pip’s installation log, or if you do a pip install -Iv MySQL_python==1.2.2 you’ll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2

The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net’s recent upgrade and PyPI’s stale URL.

So to properly install the driver, you can follow these steps:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

回答 1

您甚至可以在pip install命令中使用版本范围。像这样:

pip install 'stevedore>=1.3.0,<1.4.0'

如果该软件包已经安装,并且您想降级,请添加--force-reinstall以下内容:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

You can even use a version range with pip install command. Something like this:

pip install 'stevedore>=1.3.0,<1.4.0'

And if the package is already installed and you want to downgrade it add --force-reinstall like this:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

回答 2

一种方法,在提出这个职位,是提版本pip为:

pip install -Iv MySQL_python==1.2.2

即使用==并提及版本号以仅安装该版本。-I, --ignore-installed忽略已经安装的软件包。

One way, as suggested in this post, is to mention version in pip as:

pip install -Iv MySQL_python==1.2.2

i.e. Use == and mention the version number to install only that version. -I, --ignore-installed ignores already installed packages.


回答 3

要安装特定的python软件包版本,无论是第一次,升级还是降级,请使用:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python版本1.2.2不可用,因此我使用了其他版本。要从索引查看所有可用的软件包版本,请排除该版本:

pip install MySQL_python==

To install a specific python package version whether it is the first time, an upgrade or a downgrade use:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:

pip install MySQL_python==

回答 4

我相信,如果您已经安装了软件包,pip不会用其他版本覆盖它。使用-I忽略以前的版本。

I believe that if you already have a package it installed, pip will not overwrite it with another version. Use -I to ignore previous versions.


回答 5

有时,先前安装的版本会被缓存。

~$ pip install pillow==5.2.0

它返回以下内容:
已满足要求:/home/ubuntu/anaconda3/lib/python3.6/site-packages(5.2.0)中的pillow == 5.2.0

我们可以将–no-cache-dir与-I一起使用来覆盖它

~$ pip install --no-cache-dir -I pillow==5.2.0

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use –no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

回答 6

由于这似乎是pip版本10中引入的重大更改,因此我降级为兼容版本:

pip install 'pip<10' 

该命令告诉pip安装低于版本10的模块版本。在virutalenv中执行此操作,这样就不会增加Python站点安装的麻烦

Since this appeared to be a breaking change introduced in version 10 of pip, I downgraded to a compatible version:

pip install 'pip<10' 

This command tells pip to install a version of the module lower than version 10. Do this in a virutalenv so you don’t screw up your site installation of Python.


回答 7

我最近在使用想要记录到某处pip-I标志时遇到问题:

-I卸载继续之前的现有的包; 它将仅安装在旧版本的顶部。这意味着应将两个版本之间应删除的所有文件保留在原处。如果这些文件与其他已安装模块共享名称,则可能导致奇怪的行为。

例如,假设有一个名为的软件包package。在的一个package文件中,他们使用import datetime。现在,在中package@2.0.0,它指向标准库datetime模块,但是在中package@3.0.0,他们添加了本地语言datetime.py以替代标准库版本(无论出于何种原因)。

现在说我跑步pip install package==3.0.0,但后来意识到我实际上想要版本2.0.0。如果我现在运行pip install -I package==2.0.0datetime.py文件将不会被删除,因此任何调用import datetime都会导入错误的模块。

就我而言,这表现为奇怪的语法错误,因为该软件包的较新版本添加了仅与Python 3兼容的文件,并且当我将软件包版本降级以支持Python 2时,我继续导入仅Python-3模块。

基于此,我认为-I在更新已安装的软件包版本时,总是比使用旧软件包更可取。

I recently ran into an issue when using pip‘s -I flag that I wanted to document somewhere:

-I will not uninstall the existing package before proceeding; it will just install it on top of the old one. This means that any files that should be deleted between versions will instead be left in place. This can cause weird behavior if those files share names with other installed modules.

For example, let’s say there’s a package named package. In one of packages files, they use import datetime. Now, in package@2.0.0, this points to the standard library datetime module, but in package@3.0.0, they added a local datetime.py as a replacement for the standard library version (for whatever reason).

Now lets say I run pip install package==3.0.0, but then later realize that I actually wanted version 2.0.0. If I now run pip install -I package==2.0.0, the old datetime.py file will not be removed, so any calls to import datetime will import the wrong module.

In my case, this manifested with strange syntax errors because the newer version of the package added a file that was only compatible with Python 3, and when I downgraded package versions to support Python 2, I continued importing the Python-3-only module.

Based on this, I would argue that uninstalling the old package is always preferable to using -I when updating installed package versions.


回答 8

下面的命令对我有用

Python版本-2.7

包-python-jenkins

命令- $ pip install 'python-jenkins>=1.1.1'

This below command worked for me

Python version – 2.7

package – python-jenkins

command – $ pip install 'python-jenkins>=1.1.1'


回答 9

您可以通过两种方式安装任何版本的软件包: -A)。pip install -Iv软件包名称==版本 B)。pip install -v软件包名称==版本

为一个

在这里,如果您在安装时使用-I选项(当您不知道该软件包是否已安装时)(例如’pip install -Iv pyreadline == 2. *’之类的东西),则您将在安装新的单独的程序包,而相同的现有程序包具有不同的版本。

对于B

  1. 首先,您可能要检查是否有违反要求的情况。 点子检查

2.然后查看点子列表已经安装了什么

3.如果软件包列表中包含您要安装的特定版本的软件包,那么更好的选择是先通过pip uninstall package-name卸载该版本的软件包。

4.现在,您可以继续通过pip install -v package-name == version重新安装具有特定版本的相同软件包, 例如pip install -v pyreadline == 2. *

There are 2 ways you may install any package with version:- A). pip install -Iv package-name == version B). pip install -v package-name == version

For A

Here, if you’re using -I option while installing(when you don’t know if the package is already installed) (like ‘pip install -Iv pyreadline == 2.* ‘or something), you would be installing a new separate package with the same existing package having some different version.

For B

  1. At first, you may want to check for no broken requirements. pip check

2.and then see what’s already installed by pip list

3.if the list of the packages contain any package that you wish to install with specific version then the better option is to uninstall the package of this version first, by pip uninstall package-name

4.And now you can go ahead to reinstall the same package with a specific version, by pip install -v package-name==version e.g. pip install -v pyreadline == 2.*


回答 10

如果要更新为最新版本,但您不知道可以输入的是最新版本。

pip安装MySQL_python –upgrade

这将更新可用的最新版本的MySQL_python,您可以将其用于任何其他软件包版本。

If you want to update to latest version and you don’t know what is the latest version you can type.

pip install MySQL_python –upgrade

This will update the MySQL_python for latest version available, you can use for any other package version.


如何根据本地目录中的requirements.txt文件使用pip安装软件包?

问题:如何根据本地目录中的requirements.txt文件使用pip安装软件包?

这是问题所在

我有一个require.txt看起来像:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...

我有一个本地存档目录,其中包含所有软件包和其他软件包。

我创建了一个新的virtualenv

bin/virtualenv testing

激活它后,我尝试根据本地存档目录中的requirements.txt安装软件包。

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/

我得到一些输出,似乎表明安装正常

Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....

但后来检查发现该软件包均未正确安装。我无法导入软件包,但在virtualenv的site-packages目录中找不到任何软件包。那么出了什么问题?

Here is the problem

I have a requirements.txt that looks like:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...

I have a local archive directory containing all the packages + others.

I have created a new virtualenv with

bin/virtualenv testing

upon activating it, I tried to install the packages according to requirements.txt from the local archive directory.

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/

I got some output that seems to indicate that the installation is fine

Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....

But later check revealed none of the package is installed properly. I cannot import the package, and none is found in the site-packages directory of my virtualenv. So what went wrong?


回答 0

这对我有用:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index-忽略软件包索引(仅查看--find-linksURL)。

-f, --find-links <URL>-如果是URL或html文件的路径,请解析出指向归档文件的链接。如果是file://目录的本地路径或URL,请在目录列表中查找档案。

This works for me:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index – Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <URL> – If a URL or path to an html file, then parse for links to archives. If a local path or file:// URL that’s a directory, then look for archives in the directory listing.


回答 1

我已经阅读了上面的内容,意识到这是一个古老的问题,但它仍未完全解决,仍然位于我的Google搜索结果的顶部,因此,这是一个适用于所有人的答案:

pip install -r /path/to/requirements.txt

I’ve read the above, realize this is an old question, but it’s totally unresolved and still at the top of my google search results so here’s an answer that works for everyone:

pip install -r /path/to/requirements.txt

回答 2

为了使virtualenv将所有文件安装在requirements.txt文件中。

  1. cd到requirements.txt所在的目录
  2. 激活您的虚拟环境
  3. 运行: pip install -r requirements.txt 在您的外壳中

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

回答 3

我有一个类似的问题。我尝试了这个:

pip install -U -r requirements.txt 

(-U =更新(如果已安装))

但是问题仍然存在。我意识到缺少一些通用的开发库。

sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

我不知道这是否对您有帮助。

I had a similar problem. I tried this:

pip install -U -r requirements.txt 

(-U = update if it had already installed)

But the problem continued. I realized that some of generic libraries for development were missed.

sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

I don’t know if this would help you.


回答 4

pip install -r requirements.txt

有关更多详细信息,请检查帮助选项。

pip install --help

我们可以找到选项“ -r”

-r,–requirement从给定的需求文件安装。此选项可以多次使用。

有关一些常用的pip安装选项的更多信息:(这是pip install命令上的帮助选项)

以上是完整的选项集。请使用pip install –help获得完整的选项列表。

pip install -r requirements.txt

For further details please check the help option.

pip install --help

We can find the option ‘-r’

-r, –requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options: (This is the help option on pip install command)

Also the above is the complete set of options. Please use pip install –help for complete list of options.


回答 5

简短答案

pip install -r /path/to/requirements.txt

或其他形式:

python -m pip install -r /path/to/requirements.txt

说明

在这里,-r是的缩写--requirement,它要求pip从给定的requirements文件进行安装。

pip只有在检查了requirements文件中所有列出的项目的可用性之后,它才会开始安装,即使有一个项目也不会开始安装requirement不可用。

安装可用软件包的一种解决方法是逐一安装列出的软件包。为此使用以下命令。将显示红色警告,以通知您有关不可用的软件包的信息。

cat requirements.txt | xargs -n 1 pip install

要忽略注释(以开头的行#)和空白行,请使用:

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

Short answer

pip install -r /path/to/requirements.txt

or in another form:

python -m pip install -r /path/to/requirements.txt

Explanation

Here, -r is short form of --requirement and it asks the pip to install from the given requirements file.

pip will start installation only after checking the availability of all listed items in the requirements file and it won’t start installation even if one requirement is unavailable.

One workaround to install the available packages is installing listed packages one by one. Use the following command for that. A red color warning will be shown to notify you about the unavailable packages.

cat requirements.txt | xargs -n 1 pip install

To ignore comments (lines starting with a #) and blank lines, use:

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

回答 6

通常,您将需要从本地档案中快速安装,而无需探究PyPI。

首先,下载符合您要求的档案:

$ pip install --download <DIR> -r requirements.txt

然后,使用–find-links和安装–no-index

$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt

Often, you will want a fast install from local archives, without probing PyPI.

First, download the archives that fulfill your requirements:

$ pip install --download <DIR> -r requirements.txt

Then, install using –find-links and –no-index:

$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt

回答 7

我使用了很多系统,这些系统被开发人员“遵循他们在互联网上找到的指示”所破坏。您pip和您使用python的路径/站点程序包不同,这是非常普遍的。因此,当我遇到奇怪的事物时,我首先要做的是:

$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']

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

那是一个快乐的系统

下面是一个不愉快的系统。(或者至少是一个幸福无知的系统,导致其他人感到不高兴。)

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']

$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3

不高兴,因为pip(python3.6和)正在使用/usr/local/lib/python3.6/site-packageswhile python是(python2.7和)正在使用/usr/local/lib/python2.7/site-packages

当我要确保将要求安装到正确的 python时,请执行以下操作:

$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3

$ /usr/bin/python -m pip install -r requirements.txt

您听说过,“如果它没有损坏,请不要尝试对其进行修复。” DevOps的版本是“如果您没有破坏它并且可以解决它,请不要尝试对其进行修复。”

I work with a lot of systems that have been mucked by developers “following directions they found on the internet”. It is extremely common that your pip and your python are not looking at the same paths/site-packages. For this reason, when I encounter oddness I start by doing this:

$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']

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

That is a happy system.

Below is an unhappy system. (Or at least it’s a blissfully ignorant system that causes others to be unhappy.)

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']

$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3

It is unhappy because pip is (python3.6 and) using /usr/local/lib/python3.6/site-packages while python is (python2.7 and) using /usr/local/lib/python2.7/site-packages

When I want to make sure I’m installing requirements to the right python, I do this:

$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3

$ /usr/bin/python -m pip install -r requirements.txt

You’ve heard, “If it ain’t broke, don’t try to fix it.” The DevOps version of that is, “If you didn’t break it and you can work around it, don’t try to fix it.”


回答 8

首先,创建一个虚拟环境

在python 3.6中

virtualenv --python=/usr/bin/python3.6 <path/to/new/virtualenv/>

在python 2.7中

virtualenv --python=/usr/bin/python2.7 <path/to/new/virtualenv/>

然后激活环境并安装require.txt文件中所有可用的软件包。

source <path/to/new/virtualenv>/bin/activate
pip install -r <path/to/requirement.txt>

first of all, create a virtual environment

in python 3.6

virtualenv --python=/usr/bin/python3.6 <path/to/new/virtualenv/>

in python 2.7

virtualenv --python=/usr/bin/python2.7 <path/to/new/virtualenv/>

then activate the environment and install all the packages available in the requirement.txt file.

source <path/to/new/virtualenv>/bin/activate
pip install -r <path/to/requirement.txt>

回答 9

使用python 3在虚拟环境中安装Requirements.txt文件:

我遇到过同样的问题。我试图在虚拟环境中安装requirements.txt文件。我找到了解决方案。

最初,我以这种方式创建了虚拟环境:

virtualenv -p python3 myenv

使用以下方法激活环境:

source myenv/bin/activate

现在,我使用以下命令安装了requirements.txt:

pip3 install -r requirements.txt

安装成功,我能够导入模块。

Installing requirements.txt file inside virtual env with python 3:

I had the same issue. I was trying to install requirements.txt file inside a virtual environament. I found the solution.

Initially, I created my virtual env in this way:

virtualenv -p python3 myenv

Activate the environment using:

source myenv/bin/activate

Now I installed the requirements.txt using:

pip3 install -r requirements.txt

Installation was successful and I was able to import the modules.


回答 10

尝试这个

python -m pip install -r requirements.txt

try this

python -m pip install -r requirements.txt

回答 11

pip install --user -r requirements.txt 

要么

pip3 install --user -r requirements.txt 
pip install --user -r requirements.txt 

OR

pip3 install --user -r requirements.txt 

如何获取本地安装的Python模块列表?

问题:如何获取本地安装的Python模块列表?

我想获得Python模块的列表,这些模块在我的Python安装(UNIX服务器)中。

如何获得计算机中安装的Python模块的列表?

I would like to get a list of Python modules, which are in my Python installation (UNIX server).

How can you get a list of Python modules installed in your computer?


回答 0

不要使用pip> 10.0!

pip freeze从Python脚本中获得类似列表的50美分:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

作为(太长)一行代码:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

给予:

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

范围

该解决方案适用于系统范围或到虚拟环境范围,和封面封装安装通过setuptoolspip以及(但愿easy_install

我的用例

我将此调用的结果添加到了我的Flask服务器中,所以当我用它调用它时,http://example.com/exampleServer/environment我会获得服务器的virtualenv上安装的软件包的列表。它使调试变得非常容易。

注意事项

我注意到这种技术的奇怪行为-当Python解释器在与setup.py文件相同的目录中被调用时,它没有列出所安装的软件包setup.py

重现步骤:

创建一个虚拟环境
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
克隆一个git repo setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.

我们的行为的setup.py/tmp/behave

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
从git repo安装python包
(test_env) $ cd /tmp/behave && pip install . 
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1

如果我们从 /tmp

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'

如果我们从 /tmp/behave

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'

behave==1.2.5a1第二个示例中缺少,因为工作目录包含behavesetup.py文件。

我在文档中找不到对该问题的任何引用。也许我会为此打开一个错误。

Solution

Do not use with pip > 10.0!

My 50 cents for getting a pip freeze-like list from a Python script:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

As a (too long) one liner:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Giving:

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

Scope

This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools, pip and (god forbid) easy_install.

My use case

I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment I get the list of packages installed on the server’s virtualenv. It makes debugging a whole lot easier.

Caveats

I have noticed a strange behaviour of this technique – when the Python interpreter is invoked in the same directory as a setup.py file, it does not list the package installed by setup.py.

Steps to reproduce:

Create a virtual environment
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
Clone a git repo with setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.

We have behave’s setup.py in /tmp/behave:

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(test_env) $ cd /tmp/behave && pip install . 
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1

If we run the aforementioned solution from /tmp

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'

If we run the aforementioned solution from /tmp/behave

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'

behave==1.2.5a1 is missing from the second example, because the working directory contains behave‘s setup.py file.

I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.


回答 1

help('modules')

在Python Shell /提示中。

help('modules')

in a Python shell/prompt.


回答 2

现在,我尝试了这些方法,并且得到了所宣传的内容:所有模块。

las,真的,您对stdlib不太在乎,您知道安装python会得到什么。

说真的,我想要那个东西安装。

出乎意料的是,实际上效果很好的是:

pip freeze

哪个返回:

Fabric==0.9.3
apache-libcloud==0.4.0
bzr==2.3b4
distribute==0.6.14
docutils==0.7
greenlet==0.3.1
ipython==0.10.1
iterpipes==0.4
libxml2-python==2.6.21

我之所以说“令人惊讶”,是因为软件包安装工具是人们期望找到该功能的确切位置,尽管它的名称不是“ freeze”,但python打包却很奇怪,令我感到惊讶的是,这个工具很有意义。点0.8.2,Python 2.7。

Now, these methods I tried myself, and I got exactly what was advertised: All the modules.

Alas, really you don’t care much about the stdlib, you know what you get with a python install.

Really, I want the stuff that I installed.

What actually, surprisingly, worked just fine was:

pip freeze

Which returned:

Fabric==0.9.3
apache-libcloud==0.4.0
bzr==2.3b4
distribute==0.6.14
docutils==0.7
greenlet==0.3.1
ipython==0.10.1
iterpipes==0.4
libxml2-python==2.6.21

I say “surprisingly” because the package install tool is the exact place one would expect to find this functionality, although not under the name ‘freeze’ but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.


回答 3

从pip 1.3版开始,您可以访问:

pip list

这似乎是“点子冻结”的语法糖。它将列出特定于您的安装或virtualenv的所有模块,以及它们的版本号。不幸的是,它没有显示任何模块的当前版本号,也没有洗碗或擦鞋。

Since pip version 1.3, you’ve got access to:

pip list

Which seems to be syntactic sugar for “pip freeze”. It will list all of the modules particular to your installation or virtualenv, along with their version numbers. Unfortunately it does not display the current version number of any module, nor does it wash your dishes or shine your shoes.


回答 4

  • 在其中ipython可以输入“ importTab”。

  • 在标准的Python解释器中,您可以输入“ help('modules')”。

  • 在命令行上,您可以使用。pydoc modules

  • 在脚本中,调用pkgutil.iter_modules()

  • In ipython you can type “importTab“.

  • In the standard Python interpreter, you can type “help('modules')“.

  • At the command-line, you can use pydoc modules.

  • In a script, call pkgutil.iter_modules().


回答 5

我只是用它来查看当前使用的模块:

import sys as s
s.modules.keys()

显示所有在python上运行的模块。

对于所有内置模块,请使用:

s.modules

这是一个包含所有模块和导入对象的字典。

I just use this to see currently used modules:

import sys as s
s.modules.keys()

which shows all modules running on your python.

For all built-in modules use:

s.modules

Which is a dict containing all modules and import objects.


回答 6

在普通外壳中使用

pydoc modules

In normal shell just use

pydoc modules

回答 7

从第10点开始,接受的答案将不再起作用。开发团队已删除对get_installed_distributions例程的访问。中有一个备用功能setuptools可以完成相同的操作。这是与pip 10兼容的替代版本:

import pkg_resources
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

请让我知道它是否会在早期版本的pip中起作用。

As of pip 10, the accepted answer will no longer work. The development team has removed access to the get_installed_distributions routine. There is an alternate function in the setuptools for doing the same thing. Here is an alternate version that works with pip 10:

import pkg_resources
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

Please let me know if it will or won’t work in previous versions of pip, too.


回答 8

如果我们需要在Python Shell中列出已安装的软件包,则可以使用以下help命令

>>help('modules package')

If we need to list the installed packages in the Python shell, we can use the help command as follows

>>help('modules package')

回答 9

我通常使用pip list来获取软件包列表(带有版本)。

当然,这也可以在虚拟环境中工作。要显示仅在虚拟环境中安装的内容(而不是全局软件包),请使用pip list --local

这里的文档显示了所有可用的pip list选项,并提供了一些很好的示例。

I normally use pip list to get a list of packages (with version).

This works in a virtual environment too, of course. To show what’s installed in only the virtual environment (not global packages), use pip list --local.

Here’s documentation showing all the available pip list options, with several good examples.


回答 10

使用pkgutil.iter_modules非常简单的搜索

from pkgutil import iter_modules
a=iter_modules()
while True:
    try: x=a.next()
    except: break
    if 'searchstr' in x[1]: print x[1]

Very simple searching using pkgutil.iter_modules

from pkgutil import iter_modules
a=iter_modules()
while True:
    try: x=a.next()
    except: break
    if 'searchstr' in x[1]: print x[1]

回答 11

在Windows上,以cmd输入

c:\python\libs>python -m pip freeze

on windows, Enter this in cmd

c:\python\libs>python -m pip freeze

回答 12

我在OS X上遇到了一个自定义安装的python 2.7。它需要X11列出安装的模块(都使用help和pydoc)。

为了能够列出所有模块而不安装X11,我将pydoc作为http-server运行,即:

pydoc -p 12345

然后,可以指示Safari http://localhost:12345/浏览所有模块。

I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc).

To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.:

pydoc -p 12345

Then it’s possible to direct Safari to http://localhost:12345/ to see all modules.


回答 13

试试这些

pip list

要么

pip freeze

Try these

pip list

or

pip freeze

回答 14

这会有所帮助

在终端或IPython中,键入:

help('modules')

然后

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

This will help

In terminal or IPython, type:

help('modules')

then

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

回答 15

该解决方案主要基于模块importlibpkgutil并且可以与CPython 3.4和CPython 3.5一起使用,但是不支持CPython 2。


说明

  1. sys.builtin_module_names-命名所有内置模块(在此处查看我的答案)
  2. pkgutil.iter_modules() -返回有关所有可用模块的信息
  3. importlib.util.find_spec() -返回有关导入模块的信息(如果存在)
  4. BuiltinImporter-内置模块的导入器(docs
  5. SourceFileLoader-标准Python模块的导入程序(默认扩展名为* .py)(docs
  6. ExtensionFileLoader-将模块导入为共享库(用C或C ++编写)

完整代码

import sys
import os
import shutil
import pkgutil
import importlib
import collections

if sys.version_info.major == 2:
    raise NotImplementedError('CPython 2 is not supported yet')


def main():

    # name this file (module)
    this_module_name = os.path.basename(__file__).rsplit('.')[0]

    # dict for loaders with their modules
    loaders = collections.OrderedDict()

    # names`s of build-in modules
    for module_name in sys.builtin_module_names:

        # find an information about a module by name
        module = importlib.util.find_spec(module_name)

        # add a key about a loader in the dict, if not exists yet
        if module.loader not in loaders:
            loaders[module.loader] = []

        # add a name and a location about imported module in the dict
        loaders[module.loader].append((module.name, module.origin))

    # all available non-build-in modules
    for module_name in pkgutil.iter_modules():

        # ignore this module
        if this_module_name == module_name[1]:
            continue

        # find an information about a module by name
        module = importlib.util.find_spec(module_name[1])

        # add a key about a loader in the dict, if not exists yet
        loader = type(module.loader)
        if loader not in loaders:
            loaders[loader] = []

        # add a name and a location about imported module in the dict
        loaders[loader].append((module.name, module.origin))

    # pretty print
    line = '-' * shutil.get_terminal_size().columns
    for loader, modules in loaders.items():
        print('{0}\n{1}: {2}\n{0}'.format(line, len(modules), loader))
        for module in modules:
            print('{0:30} | {1}'.format(module[0], module[1]))


if __name__ == '__main__':
    main()

用法

对于CPython3.5(已截断)

$ python3.5 python_modules_info.py 
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
30: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast                           | built-in
_codecs                        | built-in
_collections                   | built-in
_functools                     | built-in
_imp                           | None
_io                            | built-in
_locale                        | built-in
_operator                      | built-in
_signal                        | built-in
_sre                           | built-in
_stat                          | built-in
_string                        | built-in
_symtable                      | built-in
_thread                        | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
227: <class '_frozen_importlib_external.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__                     | /usr/local/lib/python3.5/__future__.py
_bootlocale                    | /usr/local/lib/python3.5/_bootlocale.py
_collections_abc               | /usr/local/lib/python3.5/_collections_abc.py
_compat_pickle                 | /usr/local/lib/python3.5/_compat_pickle.py
_compression                   | /usr/local/lib/python3.5/_compression.py
_dummy_thread                  | /usr/local/lib/python3.5/_dummy_thread.py
_markupbase                    | /usr/local/lib/python3.5/_markupbase.py
_osx_support                   | /usr/local/lib/python3.5/_osx_support.py
_pydecimal                     | /usr/local/lib/python3.5/_pydecimal.py
_pyio                          | /usr/local/lib/python3.5/_pyio.py
_sitebuiltins                  | /usr/local/lib/python3.5/_sitebuiltins.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
64: <class '_frozen_importlib_external.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bisect                        | /usr/local/lib/python3.5/lib-dynload/_bisect.cpython-35m-x86_64-linux-gnu.so
_bz2                           | /usr/local/lib/python3.5/lib-dynload/_bz2.cpython-35m-x86_64-linux-gnu.so
_codecs_cn                     | /usr/local/lib/python3.5/lib-dynload/_codecs_cn.cpython-35m-x86_64-linux-gnu.so
_codecs_hk                     | /usr/local/lib/python3.5/lib-dynload/_codecs_hk.cpython-35m-x86_64-linux-gnu.so
_codecs_iso2022                | /usr/local/lib/python3.5/lib-dynload/_codecs_iso2022.cpython-35m-x86_64-linux-gnu.so
(****************************truncated*******************************)

对于CPython3.4(已截断)

$ python3.4 python_modules_info.py
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
54: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast                           | built-in
_bisect                        | built-in
_codecs                        | built-in
_collections                   | built-in
_datetime                      | built-in
_elementtree                   | built-in
_functools                     | built-in
_heapq                         | built-in
_imp                           | None
_io                            | built-in
_locale                        | built-in
_md5                           | built-in
_operator                      | built-in
_pickle                        | built-in
_posixsubprocess               | built-in
_random                        | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
246: <class '_frozen_importlib.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__                     | /usr/lib/python3.4/__future__.py
_bootlocale                    | /usr/lib/python3.4/_bootlocale.py
_collections_abc               | /usr/lib/python3.4/_collections_abc.py
_compat_pickle                 | /usr/lib/python3.4/_compat_pickle.py
_dummy_thread                  | /usr/lib/python3.4/_dummy_thread.py
_markupbase                    | /usr/lib/python3.4/_markupbase.py
_osx_support                   | /usr/lib/python3.4/_osx_support.py
_pyio                          | /usr/lib/python3.4/_pyio.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
44: <class '_frozen_importlib.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bz2                           | /usr/lib/python3.4/lib-dynload/_bz2.cpython-34m-x86_64-linux-gnu.so
_codecs_cn                     | /usr/lib/python3.4/lib-dynload/_codecs_cn.cpython-34m-x86_64-linux-gnu.so
_codecs_hk                     | /usr/lib/python3.4/lib-dynload/_codecs_hk.cpython-34m-x86_64-linux-gnu.so
_codecs_iso2022                | /usr/lib/python3.4/lib-dynload/_codecs_iso2022.cpython-34m-x86_64-linux-gnu.so
_codecs_jp                     | /usr/lib/python3.4/lib-dynload/_codecs_jp.cpython-34m-x86_64-linux-gnu.so
_codecs_kr                     | /usr/lib/python3.4/lib-dynload/_codecs_kr.cpython-34m-x86_64-linux-gnu.so
_codecs_tw                     | /usr/lib/python3.4/lib-dynload/_codecs_tw.cpython-34m-x86_64-linux-gnu.so
_crypt                         | /usr/lib/python3.4/lib-dynload/_crypt.cpython-34m-x86_64-linux-gnu.so
(****************************truncated*******************************)

This solution is primary based on modules importlib and pkgutil and work with CPython 3.4 and CPython 3.5, but has no support for the CPython 2.


Explanation

  1. sys.builtin_module_names – names all built-in modules (look my answer here)
  2. pkgutil.iter_modules() – returns an information about all available modules
  3. importlib.util.find_spec() – returns an information about importing module, if exists
  4. BuiltinImporter – an importer for built-in modules (docs)
  5. SourceFileLoader – an importer for a standard Python module (by default has extension *.py) (docs)
  6. ExtensionFileLoader – an importer for modules as shared library (written on the C or C++)

Full code

import sys
import os
import shutil
import pkgutil
import importlib
import collections

if sys.version_info.major == 2:
    raise NotImplementedError('CPython 2 is not supported yet')


def main():

    # name this file (module)
    this_module_name = os.path.basename(__file__).rsplit('.')[0]

    # dict for loaders with their modules
    loaders = collections.OrderedDict()

    # names`s of build-in modules
    for module_name in sys.builtin_module_names:

        # find an information about a module by name
        module = importlib.util.find_spec(module_name)

        # add a key about a loader in the dict, if not exists yet
        if module.loader not in loaders:
            loaders[module.loader] = []

        # add a name and a location about imported module in the dict
        loaders[module.loader].append((module.name, module.origin))

    # all available non-build-in modules
    for module_name in pkgutil.iter_modules():

        # ignore this module
        if this_module_name == module_name[1]:
            continue

        # find an information about a module by name
        module = importlib.util.find_spec(module_name[1])

        # add a key about a loader in the dict, if not exists yet
        loader = type(module.loader)
        if loader not in loaders:
            loaders[loader] = []

        # add a name and a location about imported module in the dict
        loaders[loader].append((module.name, module.origin))

    # pretty print
    line = '-' * shutil.get_terminal_size().columns
    for loader, modules in loaders.items():
        print('{0}\n{1}: {2}\n{0}'.format(line, len(modules), loader))
        for module in modules:
            print('{0:30} | {1}'.format(module[0], module[1]))


if __name__ == '__main__':
    main()

Usage

For the CPython3.5 (truncated)

$ python3.5 python_modules_info.py 
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
30: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast                           | built-in
_codecs                        | built-in
_collections                   | built-in
_functools                     | built-in
_imp                           | None
_io                            | built-in
_locale                        | built-in
_operator                      | built-in
_signal                        | built-in
_sre                           | built-in
_stat                          | built-in
_string                        | built-in
_symtable                      | built-in
_thread                        | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
227: <class '_frozen_importlib_external.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__                     | /usr/local/lib/python3.5/__future__.py
_bootlocale                    | /usr/local/lib/python3.5/_bootlocale.py
_collections_abc               | /usr/local/lib/python3.5/_collections_abc.py
_compat_pickle                 | /usr/local/lib/python3.5/_compat_pickle.py
_compression                   | /usr/local/lib/python3.5/_compression.py
_dummy_thread                  | /usr/local/lib/python3.5/_dummy_thread.py
_markupbase                    | /usr/local/lib/python3.5/_markupbase.py
_osx_support                   | /usr/local/lib/python3.5/_osx_support.py
_pydecimal                     | /usr/local/lib/python3.5/_pydecimal.py
_pyio                          | /usr/local/lib/python3.5/_pyio.py
_sitebuiltins                  | /usr/local/lib/python3.5/_sitebuiltins.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
64: <class '_frozen_importlib_external.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bisect                        | /usr/local/lib/python3.5/lib-dynload/_bisect.cpython-35m-x86_64-linux-gnu.so
_bz2                           | /usr/local/lib/python3.5/lib-dynload/_bz2.cpython-35m-x86_64-linux-gnu.so
_codecs_cn                     | /usr/local/lib/python3.5/lib-dynload/_codecs_cn.cpython-35m-x86_64-linux-gnu.so
_codecs_hk                     | /usr/local/lib/python3.5/lib-dynload/_codecs_hk.cpython-35m-x86_64-linux-gnu.so
_codecs_iso2022                | /usr/local/lib/python3.5/lib-dynload/_codecs_iso2022.cpython-35m-x86_64-linux-gnu.so
(****************************truncated*******************************)

For the CPython3.4 (truncated)

$ python3.4 python_modules_info.py
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
54: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast                           | built-in
_bisect                        | built-in
_codecs                        | built-in
_collections                   | built-in
_datetime                      | built-in
_elementtree                   | built-in
_functools                     | built-in
_heapq                         | built-in
_imp                           | None
_io                            | built-in
_locale                        | built-in
_md5                           | built-in
_operator                      | built-in
_pickle                        | built-in
_posixsubprocess               | built-in
_random                        | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
246: <class '_frozen_importlib.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__                     | /usr/lib/python3.4/__future__.py
_bootlocale                    | /usr/lib/python3.4/_bootlocale.py
_collections_abc               | /usr/lib/python3.4/_collections_abc.py
_compat_pickle                 | /usr/lib/python3.4/_compat_pickle.py
_dummy_thread                  | /usr/lib/python3.4/_dummy_thread.py
_markupbase                    | /usr/lib/python3.4/_markupbase.py
_osx_support                   | /usr/lib/python3.4/_osx_support.py
_pyio                          | /usr/lib/python3.4/_pyio.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
44: <class '_frozen_importlib.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bz2                           | /usr/lib/python3.4/lib-dynload/_bz2.cpython-34m-x86_64-linux-gnu.so
_codecs_cn                     | /usr/lib/python3.4/lib-dynload/_codecs_cn.cpython-34m-x86_64-linux-gnu.so
_codecs_hk                     | /usr/lib/python3.4/lib-dynload/_codecs_hk.cpython-34m-x86_64-linux-gnu.so
_codecs_iso2022                | /usr/lib/python3.4/lib-dynload/_codecs_iso2022.cpython-34m-x86_64-linux-gnu.so
_codecs_jp                     | /usr/lib/python3.4/lib-dynload/_codecs_jp.cpython-34m-x86_64-linux-gnu.so
_codecs_kr                     | /usr/lib/python3.4/lib-dynload/_codecs_kr.cpython-34m-x86_64-linux-gnu.so
_codecs_tw                     | /usr/lib/python3.4/lib-dynload/_codecs_tw.cpython-34m-x86_64-linux-gnu.so
_crypt                         | /usr/lib/python3.4/lib-dynload/_crypt.cpython-34m-x86_64-linux-gnu.so
(****************************truncated*******************************)

回答 16

警告:亚当·马坦(Adam Matan)不建议在点> 10.0的情况下使用此方法。另外,请在下面阅读@sinoroc的评论

这是受到亚当·马坦(Adam Matan)的回答(公认的)的启发:

import tabulate
try:
  from pip import get_installed_distributions
except:
  from pip._internal.utils.misc import get_installed_distributions

tabpackages = []
for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]):
  tabpackages.append([package.location, package.key, package.version])

print(tabulate.tabulate(tabpackages))

然后以以下形式打印出表格

19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py
-------------------------------------------  --------------  ------
/home/pi/.local/lib/python2.7/site-packages  enum-compat     0.0.2
/home/pi/.local/lib/python2.7/site-packages  enum34          1.1.6
/home/pi/.local/lib/python2.7/site-packages  pexpect         4.2.1
/home/pi/.local/lib/python2.7/site-packages  ptyprocess      0.5.2
/home/pi/.local/lib/python2.7/site-packages  pygatt          3.2.0
/home/pi/.local/lib/python2.7/site-packages  pyserial        3.4
/usr/local/lib/python2.7/dist-packages       bluepy          1.1.1
/usr/local/lib/python2.7/dist-packages       click           6.7
/usr/local/lib/python2.7/dist-packages       click-datetime  0.2
/usr/local/lib/python2.7/dist-packages       construct       2.8.21
/usr/local/lib/python2.7/dist-packages       pyaudio         0.2.11
/usr/local/lib/python2.7/dist-packages       tabulate        0.8.2
-------------------------------------------  --------------  ------

这样一来,您便可以轻松辨别使用和不安装时安装的软件包sudo


撇开笔记:我注意到,当我一次安装一个数据包而一次安装一次数据包时sudo,一个优先处理,这样就不会列出另一个数据包(仅显示一个位置)。我相信只会列出本地目录中的一个。这可以改善。

Warning: Adam Matan discourages this use in pip > 10.0. Also, read @sinoroc’s comment below

This was inspired by Adam Matan’s answer (the accepted one):

import tabulate
try:
  from pip import get_installed_distributions
except:
  from pip._internal.utils.misc import get_installed_distributions

tabpackages = []
for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]):
  tabpackages.append([package.location, package.key, package.version])

print(tabulate.tabulate(tabpackages))

which then prints out a table in the form of

19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py
-------------------------------------------  --------------  ------
/home/pi/.local/lib/python2.7/site-packages  enum-compat     0.0.2
/home/pi/.local/lib/python2.7/site-packages  enum34          1.1.6
/home/pi/.local/lib/python2.7/site-packages  pexpect         4.2.1
/home/pi/.local/lib/python2.7/site-packages  ptyprocess      0.5.2
/home/pi/.local/lib/python2.7/site-packages  pygatt          3.2.0
/home/pi/.local/lib/python2.7/site-packages  pyserial        3.4
/usr/local/lib/python2.7/dist-packages       bluepy          1.1.1
/usr/local/lib/python2.7/dist-packages       click           6.7
/usr/local/lib/python2.7/dist-packages       click-datetime  0.2
/usr/local/lib/python2.7/dist-packages       construct       2.8.21
/usr/local/lib/python2.7/dist-packages       pyaudio         0.2.11
/usr/local/lib/python2.7/dist-packages       tabulate        0.8.2
-------------------------------------------  --------------  ------

which lets you then easily discern which packages you installed with and without sudo.


A note aside: I’ve noticed that when I install a packet once via sudo and once without, one takes precedence so that the other one isn’t being listed (only one location is shown). I believe that only the one in the local directory is then listed. This could be improved.


回答 17

除了使用之外,pip freeze我还在虚拟环境中安装了蛋黄

Aside from using pip freeze I have been installing yolk in my virtual environments.


回答 18

如果您安装了anaconda python发行版,则也可以使用

$conda list

除了上述解决方案。

In case you have an anaconda python distribution installed, you could also use

$conda list

in addition to solutions described above.


回答 19

  1. 获取所有可用的模块,运行 sys.modules
  2. 要获取所有已安装的模块(请阅读:由by安装pip),您可以查看pip.get_installed_distributions()

出于第二个目的,示例代码:

import pip
for package in pip.get_installed_distributions():
    name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib
    key = package.key # sqlalchemy, django, flask-oauthlib
    module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib
    location = package.location # virtualenv lib directory etc.
    version = package.version # version number
  1. to get all available modules, run sys.modules
  2. to get all installed modules (read: installed by pip), you may look at pip.get_installed_distributions()

For the second purpose, example code:

import pip
for package in pip.get_installed_distributions():
    name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib
    key = package.key # sqlalchemy, django, flask-oauthlib
    module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib
    location = package.location # virtualenv lib directory etc.
    version = package.version # version number

回答 20

对于最新版本,例如Pip 20

在您的python编辑器或IPython中运行以下命令

import pkg_resources; 
installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}
print(installed_packages)

阅读其他答案并组合在一起,这是Python中最快,最简单的组合

For Recent Version Such as Pip 20

Run the following in your python editor or IPython

import pkg_resources; 
installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}
print(installed_packages)

Read other answers and pulled together this combo, which is quickest and easiest inside Python


回答 21

pip Frozen完成了所有查找程序包的工作,但是只需编写以下命令即可列出python程序包所在的所有路径。

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

pip freeze does it all finding packages however one can simply write the following command to list all paths where python packages are.

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

回答 22

有很多方法可以给猫皮。

  • 最简单的方法是pydoc直接在shell中使用以下功能:
    pydoc modules

  • 但是,有关更多信息,请使用名为pip-date的工具,该工具还会告诉您安装日期。
    pip install pip-date


There are many way to skin a cat.

  • The most simple way is to use the pydoc function directly from the shell with:
    pydoc modules

  • But for more information use the tool called pip-date that also tell you the installation dates.
    pip install pip-date



回答 23

有很多想法,最初我会考虑以下两个方面:

点子

缺点:并非总是安装

帮助(’模块’)

缺点:输出到控制台;带有损坏的模块(请参见ubuntu …)会导致segfault

我需要一个简单的方法,使用基本库并与旧python 2.x兼容

我看到了光:listmodules.py

2.5的文档源目录中隐藏着一个小脚本,该脚本列出了Python安装的所有可用模块。

优点:

仅使用imp,sys,os,re,time

设计用于在Python 1.5.2和更高版本上运行

源代码确实非常紧凑,因此您可以轻松修改它,例如,传递错误模块的异常列表(不要尝试导入它们)

There are many ideas, initially I am pondering on these two:

pip

cons: not always installed

help(‘modules’)

cons: output to console; with broken modules (see ubuntu…) can segfault

I need an easy approach, using basic libraries and compatible with old python 2.x

And I see the light: listmodules.py

Hidden in the documentation source directory in 2.5 is a small script that lists all available modules for a Python installation.

Pros:

uses only imp, sys, os, re, time

designed to run on Python 1.5.2 and newer

the source code is really compact, so you can easy tinkering with it, for example to pass an exception list of buggy modules (don’t try to import them)


回答 24

我需要找到AWS Lambda默认可用的特定版本的软件包。我是通过此页面上的想法混搭来实现的。我分享是为了后代。

import pkgutil

__version__ = '0.1.1'

def get_ver(name):
    try:
        return str(__import__(name).__version__)
    except:
        return None

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': [{
                   'path': m.module_finder.path,
                   'name': m.name,
                   'version': get_ver(m.name),
                 } for m in list(pkgutil.iter_modules())
                 #if m.module_finder.path == "/var/runtime" # Uncomment this if you only care about a certain path
                ],
    }

我发现所提供的boto3库已过时,并且我的代码失败不是我的错。我只需要在项目中添加boto3和botocore。但是如果没有这个,我本来会以为我的代码很糟糕而ing之以鼻。

{
  "statusCode": 200,
  "body": [
    {
      "path": "/var/task",
      "name": "lambda_function",
      "version": "0.1.1"
    },
    {
      "path": "/var/runtime",
      "name": "bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "boto3",
      "version": "1.9.42"
    },
    {
      "path": "/var/runtime",
      "name": "botocore",
      "version": "1.12.42"
    },
    {
      "path": "/var/runtime",
      "name": "dateutil",
      "version": "2.7.5"
    },
    {
      "path": "/var/runtime",
      "name": "docutils",
      "version": "0.14"
    },
    {
      "path": "/var/runtime",
      "name": "jmespath",
      "version": "0.9.3"
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_exception",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "s3transfer",
      "version": "0.1.13"
    },
    {
      "path": "/var/runtime",
      "name": "six",
      "version": "1.11.0"
    },
    {
      "path": "/var/runtime",
      "name": "test_bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "urllib3",
      "version": "1.24.1"
    },
    {
      "path": "/var/lang/lib/python3.7",
      "name": "__future__",
      "version": null
    },
...

我发现的内容也与他们正式发布的内容不同。在撰写本文时:

  • 操作系统– Amazon Linux
  • AMI – amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2
  • Linux内核– 4.14.77-70.59.amzn1.x86_64
  • 适用于JavaScript的AWS开发工具包– 2.290.0 \
  • 适用于Python的SDK(Boto 3)– 3-1.7.74 botocore-1.10.74

I needed to find the specific version of packages available by default in AWS Lambda. I did so with a mashup of ideas from this page. I’m sharing it for posterity.

import pkgutil

__version__ = '0.1.1'

def get_ver(name):
    try:
        return str(__import__(name).__version__)
    except:
        return None

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': [{
                   'path': m.module_finder.path,
                   'name': m.name,
                   'version': get_ver(m.name),
                 } for m in list(pkgutil.iter_modules())
                 #if m.module_finder.path == "/var/runtime" # Uncomment this if you only care about a certain path
                ],
    }

What I discovered is that the provided boto3 library was way out of date and it wasn’t my fault that my code was failing. I just needed to add boto3 and botocore to my project. But without this I would have been banging my head thinking my code was bad.

{
  "statusCode": 200,
  "body": [
    {
      "path": "/var/task",
      "name": "lambda_function",
      "version": "0.1.1"
    },
    {
      "path": "/var/runtime",
      "name": "bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "boto3",
      "version": "1.9.42"
    },
    {
      "path": "/var/runtime",
      "name": "botocore",
      "version": "1.12.42"
    },
    {
      "path": "/var/runtime",
      "name": "dateutil",
      "version": "2.7.5"
    },
    {
      "path": "/var/runtime",
      "name": "docutils",
      "version": "0.14"
    },
    {
      "path": "/var/runtime",
      "name": "jmespath",
      "version": "0.9.3"
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_exception",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "s3transfer",
      "version": "0.1.13"
    },
    {
      "path": "/var/runtime",
      "name": "six",
      "version": "1.11.0"
    },
    {
      "path": "/var/runtime",
      "name": "test_bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "urllib3",
      "version": "1.24.1"
    },
    {
      "path": "/var/lang/lib/python3.7",
      "name": "__future__",
      "version": null
    },
...

What I discovered was also different from what they officially publish. At the time of writing this:

  • Operating system – Amazon Linux
  • AMI – amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2
  • Linux kernel – 4.14.77-70.59.amzn1.x86_64
  • AWS SDK for JavaScript – 2.290.0\
  • SDK for Python (Boto 3) – 3-1.7.74 botocore-1.10.74

回答 25

安装

pip install pkgutil

import pkgutil

for i in pkgutil.iter_modules(None): # returns a tuple (path, package_name, ispkg_flag)
    print(i[1]) #or you can append it to a list

样本输出:

multiprocessing
netrc
nntplib
ntpath
nturl2path
numbers
opcode
pickle
pickletools
pipes
pkgutil

Installation

pip install pkgutil

Code

import pkgutil

for i in pkgutil.iter_modules(None): # returns a tuple (path, package_name, ispkg_flag)
    print(i[1]) #or you can append it to a list

Sample Output:

multiprocessing
netrc
nntplib
ntpath
nturl2path
numbers
opcode
pickle
pickletools
pipes
pkgutil

回答 26

这是一个python代码解决方案,它将返回已安装模块的列表。可以轻松地修改代码以包含版本号。

import subprocess
import sys
from pprint import pprint

installed_packages = reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')
installed_packages = installed_packages.split('\r\n')
installed_packages = [pkg.split('==')[0] for pkg in installed_packages if pkg != '']
pprint(installed_packages)

Here is a python code solution that will return a list of modules installed. One can easily modify the code to include version numbers.

import subprocess
import sys
from pprint import pprint

installed_packages = reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')
installed_packages = installed_packages.split('\r\n')
installed_packages = [pkg.split('==')[0] for pkg in installed_packages if pkg != '']
pprint(installed_packages)

回答 27

对于想知道如何pip list从Python程序调用的任何人,可以使用以下命令:

import pip
pip.main(['list])  # this will print all the packages

For anyone wondering how to call pip list from a Python program you can use the following:

import pip
pip.main(['list])  # this will print all the packages

回答 28

从外壳

ls site-packages

如果那没有帮助,则可以执行此操作。

import sys
import os
for p in sys.path:
    print os.listdir( p )

看看会产生什么。

From the shell

ls site-packages

If that’s not helpful, you can do this.

import sys
import os
for p in sys.path:
    print os.listdir( p )

And see what that produces.


如何在Windows上安装pip?

问题:如何在Windows上安装pip?

pip是的替代品easy_install。但是我应该在Windows上pip使用安装easy_install吗?有没有更好的办法?

pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?


回答 0

Python 2.7.9+和3.4+

好消息!Pip随附了Python 3.4(2014年3月发布)和Python 2.7.9(2014年12月发布)。这是所有Python版本中的最佳功能。它使每个人都可以访问社区丰富的图书馆。新手不再因设置的困难而无法使用社区库。在与软件包管理器一起交付时,Python加入了RubyNode.jsHaskellPerlGo以及几乎所有其他具有主流开源社区的当代语言。谢谢,Python。

如果确实发现在使用Python 3.4+或Python 2.7.9+时不可用pip,则只需执行例如:

py -3 -m ensurepip

当然,这并不意味着Python打包已解决问题。经验仍然令人沮丧。我将在“堆栈溢出”问题中对此进行讨论。Python是否具有程序包/模块管理系统?

而且,对使用Python 2.7.8或更早版本(社区中相当大的一部分)的每个人来说都可惜。没有计划将Pip运送给您。遵循手册说明。

Python 2≤2.7.8和Python 3≤3.3

面对“包括电池”的座右铭,Python出厂时没有软件包管理器。更糟糕的是,直到最近,Pip一直很难安装。

官方指示

根据https://pip.pypa.io/zh-CN/stable/installing/#do-i-need-to-install-pip

下载时get-pip.py,请小心保存为.py文件而不是文件.txt。然后,在命令提示符下运行它:

python get-pip.py

您可能需要管理员命令提示符才能执行此操作。按照以管理员身份启动命令提示符(Microsoft TechNet)。

这将安装pip程序包,该程序包(在Windows中)包含… \ Scripts \ pip.exe,该路径必须位于PATH环境变量中才能从命令行使用pip(请参阅“替代说明”的第二部分,将其添加到您的路径,

替代说明

官方文档告诉用户从源代码安装Pip及其每个依赖项。对于新手来说,这是乏味的,对新手来说却是困难重重。

为了我们的缘故,Christoph Gohlke .msi为流行的Python软件包准备了Windows安装程序()。他为所有32位和64位Python版本构建安装程序。你需要:

  1. 安装setuptools
  2. 安装点子

对我来说,此安装点位于C:\Python27\Scripts\pip.exepip.exe在您的计算机上查找,然后将其文件夹(例如C:\Python27\Scripts)添加到您的路径(开始/编辑环境变量)。现在,您应该可以从命令行运行pip了。尝试安装软件包:

pip install httpie

你去了(希望)!常见问题的解决方案如下:

代理问题

如果您在办公室工作,则可能位于HTTP代理后面。如果是这样,请设置环境变量http_proxyhttps_proxy。大多数Python应用程序(和其他免费软件)都遵守这些规定。语法示例:

http://proxy_url:port
http://username:password@proxy_url:port

如果您真的不走运,则您的代理可以是Microsoft NTLM代理。自由软件无法应付。唯一的解决方案是安装一个免费软件友好代理,该代理转发给讨厌的代理。http://cntlm.sourceforge.net/

找不到vcvarsall.bat

Python模块可以部分用C或C ++编写。Pip尝试从源代码进行编译。如果没有安装和配置C / C ++编译器,则会看到此错误消息。

错误:找不到vcvarsall.bat

您可以通过安装C ++编译器(例如MinGWVisual C ++)来解决此问题。微软实际上提供了一个专门用于Python的工具。或尝试使用Microsoft Visual C ++编译器Python 2.7

尽管通常更容易检查Christoph网站上的包裹。

Python 2.7.9+ and 3.4+

Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community’s wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Node.js, Haskell, Perl, Go—almost every other contemporary language with a majority open-source community. Thank you, Python.

If you do find that pip is not available when using Python 3.4+ or Python 2.7.9+, simply execute e.g.:

py -3 -m ensurepip

Of course, that doesn’t mean Python packaging is problem solved. The experience remains frustrating. I discuss this in the Stack Overflow question Does Python have a package/module management system?.

And, alas for everyone using Python 2.7.8 or earlier (a sizable portion of the community). There’s no plan to ship Pip to you. Manual instructions follow.

Python 2 ≤ 2.7.8 and Python 3 ≤ 3.3

Flying in the face of its ‘batteries included’ motto, Python ships without a package manager. To make matters worse, Pip was—until recently—ironically difficult to install.

Official instructions

Per https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip:

Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt:

python get-pip.py

You possibly need an administrator command prompt to do this. Follow Start a Command Prompt as an Administrator (Microsoft TechNet).

This installs the pip package, which (in Windows) contains …\Scripts\pip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of ‘Alternative Instructions’ for adding it to your PATH,

Alternative instructions

The official documentation tells users to install Pip and each of its dependencies from source. That’s tedious for the experienced and prohibitively difficult for newbies.

For our sake, Christoph Gohlke prepares Windows installers (.msi) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:

  1. Install setuptools
  2. Install pip

For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (for example, C:\Python27\Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:

pip install httpie

There you go (hopefully)! Solutions for common problems are given below:

Proxy problems

If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables http_proxy and https_proxy. Most Python applications (and other free software) respect these. Example syntax:

http://proxy_url:port
http://username:password@proxy_url:port

If you’re really unlucky, your proxy might be a Microsoft NTLM proxy. Free software can’t cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. http://cntlm.sourceforge.net/

Unable to find vcvarsall.bat

Python modules can be partly written in C or C++. Pip tries to compile from source. If you don’t have a C/C++ compiler installed and configured, you’ll see this cryptic error message.

Error: Unable to find vcvarsall.bat

You can fix that by installing a C++ compiler such as MinGW or Visual C++. Microsoft actually ships one specifically for use with Python. Or try Microsoft Visual C++ Compiler for Python 2.7.

Often though it’s easier to check Christoph’s site for your package.


回答 1

过时的 -使用分发,而不是此处所述的setuptools。-
过时的#2 -使用作为setuptools的分配已经过时了。

如前所述,pip不包含独立的安装程序,但是您可以使用其前身easy_install进行安装。

所以:

  1. 从此处下载最新的pip版本:http : //pypi.python.org/pypi/pip#downloads
  2. 解压缩
  3. 下载适用于Windows的最后一个简易安装程序:(http://pypi.python.org/pypi/setuptools底部下载.exe)。安装它。
  4. 将未压缩的pip文件夹内容复制到C:\Python2x\文件夹中(不要将整个文件夹复制到其中,仅复制内容),因为python命令在C:\Python2x文件夹外部不起作用,然后运行: python setup.py install
  5. 将您的python添加C:\Python2x\Scripts到路径

大功告成

现在,您可以pip install package像在Linux中那样轻松地安装软件包:)

Outdated — use distribute, not setuptools as described here. —
Outdated #2 — use setuptools as distribute is deprecated.

As you mentioned pip doesn’t include an independent installer, but you can install it with its predecessor easy_install.

So:

  1. Download the last pip version from here: http://pypi.python.org/pypi/pip#downloads
  2. Uncompress it
  3. Download the last easy installer for Windows: (download the .exe at the bottom of http://pypi.python.org/pypi/setuptools ). Install it.
  4. copy the uncompressed pip folder content into C:\Python2x\ folder (don’t copy the whole folder into it, just the content), because python command doesn’t work outside C:\Python2x folder and then run: python setup.py install
  5. Add your python C:\Python2x\Scripts to the path

You are done.

Now you can use pip install package to easily install packages as in Linux :)


回答 2

2014年更新:

1)如果您安装了Python 3.4或更高版本,则pip包含在Python中,并且应该已经在您的系统上运行。

2)如果您运行的版本低于Python 3.4,或者由于某些原因未在Python 3.4中安装pip,则您可能会使用pip的官方安装脚本get-pip.py。pip安装程序现在可以为您获取setuptools,并且可以在不考虑体系结构(32位或64位)的情况下运行。

这里详细说明了安装说明,其中包括:

要安装或升级pip,请安全下载get-pip.py

然后运行以下命令(可能需要管理员访问权限):

python get-pip.py

要升级现有的设置工具(或分发),请运行 pip install -U setuptools

为了后代,我将在下面保留两组旧说明。

旧答案:

对于Windows版本的64位版本-由于ez_setup,64位Windows + Python以前需要使用单独的安装方法,但是我已经在运行32位Python和64位Python的64位Windows上测试了新的分发方法,现在您可以对所有版本的Windows / Python 2.7X使用相同的方法:

使用分配的OLD方法2

  1. 下载分发 -我投入了我的想法C:\Python27\ScriptsScripts如果目录不存在,请随意创建。
  2. 打开命令提示符(在Windows上,如果不使用PowerShell,则应检出connemu2),然后将()更改为下载到的目录。cddistribute_setup.py
  3. 运行distribute_setup :(python distribute_setup.py如果您的python安装目录未添加到路径中,则此方法将不起作用- 请在此处获得帮助
  4. 将当前目录更改Scripts为Python安装目录(C:\Python27\Scripts),或者将该目录以及Python基本安装目录添加至您的%PATH%环境变量。
  5. 使用新安装的setuptools安装pip: easy_install pip

除非您easy_install.exe位于目录中(C:\ Python27 \ Scripts将是Python 2.7的默认设置),或者您将该目录添加到路径中,否则最后一步将不起作用。

使用ez_setup的OLD方法1

从setuptools页面

下载ez_setup.py并运行它;它将下载适当的.egg文件并为您安装。(当前,由于distutils安装程序的兼容性问题,提供的.exe安装程序不支持Windows的64位版本的Python。

之后,您可以继续:

  1. 添加c:\Python2x\Scripts到Windows路径(用已安装的实际版本号替换xin Python2x
  2. 打开一个新的(!)DOS提示符。从那里运行easy_install pip

2014 UPDATE:

1) If you have installed Python 3.4 or later, pip is included with Python and should already be working on your system.

2) If you are running a version below Python 3.4 or if pip was not installed with Python 3.4 for some reason, then you’d probably use pip’s official installation script get-pip.py. The pip installer now grabs setuptools for you, and works regardless of architecture (32-bit or 64-bit).

The installation instructions are detailed here and involve:

To install or upgrade pip, securely download get-pip.py.

Then run the following (which may require administrator access):

python get-pip.py

To upgrade an existing setuptools (or distribute), run pip install -U setuptools

I’ll leave the two sets of old instructions below for posterity.

OLD Answers:

For Windows editions of the 64 bit variety – 64-bit Windows + Python used to require a separate installation method due to ez_setup, but I’ve tested the new distribute method on 64-bit Windows running 32-bit Python and 64-bit Python, and you can now use the same method for all versions of Windows/Python 2.7X:

OLD Method 2 using distribute:

  1. Download distribute – I threw mine in C:\Python27\Scripts (feel free to create a Scripts directory if it doesn’t exist.
  2. Open up a command prompt (on Windows you should check out conemu2 if you don’t use PowerShell) and change (cd) to the directory you’ve downloaded distribute_setup.py to.
  3. Run distribute_setup: python distribute_setup.py (This will not work if your python installation directory is not added to your path – go here for help)
  4. Change the current directory to the Scripts directory for your Python installation (C:\Python27\Scripts) or add that directory, as well as the Python base installation directory to your %PATH% environment variable.
  5. Install pip using the newly installed setuptools: easy_install pip

The last step will not work unless you’re either in the directory easy_install.exe is located in (C:\Python27\Scripts would be the default for Python 2.7), or you have that directory added to your path.

OLD Method 1 using ez_setup:

from the setuptools page

Download ez_setup.py and run it; it will download the appropriate .egg file and install it for you. (Currently, the provided .exe installer does not support 64-bit versions of Python for Windows, due to a distutils installer compatibility issue.

After this, you may continue with:

  1. Add c:\Python2x\Scripts to the Windows path (replace the x in Python2x with the actual version number you have installed)
  2. Open a new (!) DOS prompt. From there run easy_install pip

回答 3

2016年更新:

这些答案已经过时,或者罗word且困难。

如果您拥有Python 3.4+或2.7.9+,它将默认安装在Windows上。否则,简而言之:

  1. 下载pip安装程序:https : //bootstrap.pypa.io/get-pip.py
  2. 如果偏执,请检查文件以确认它不是恶意的(必须b64解码)。
  3. 以Admin身份在下载文件夹中打开一个控制台,然后运行 get-pip.py。或者,在资源管理器中右键单击其图标,然后选择“以管理员身份运行…”。

新的二进制文件pip.exe(和已弃用的easy_install.exe)将在"%ProgramFiles%\PythonXX\Scripts"文件夹(或类似文件)中找到,该文件夹通常不在您的PATH变量中。我建议添加它。

2016+ Update:

These answers are outdated or otherwise wordy and difficult.

If you’ve got Python 3.4+ or 2.7.9+, it will be installed by default on Windows. Otherwise, in short:

  1. Download the pip installer: https://bootstrap.pypa.io/get-pip.py
  2. If paranoid, inspect file to confirm it isn’t malicious (must b64 decode).
  3. Open a console in the download folder as Admin and run get-pip.py. Alternatively, right-click its icon in Explorer and choose the “run as Admin…”.

The new binaries pip.exe (and the deprecated easy_install.exe) will be found in the "%ProgramFiles%\PythonXX\Scripts" folder (or similar), which is often not in your PATH variable. I recommend adding it.


回答 4

2014年3月 发布的Python 3.4 pip附带了以下内容:
http : //docs.python.org/3.4/whatsnew/3.4.html
因此,自Python 3.4发布以来,最新的安装pip方法在Windows上只是安装Python。

推荐的使用方式是将其称为模块,尤其是在安装了多个python发行版或版本的情况下,以确保程序包可以到达正确的位置:
python -m pip install --upgrade packageXYZ

https://docs.python.org/3/installing/#work-with-multiple-versions-of-python-installed-in-parallel

Python 3.4, which was released in March 2014, comes with pip included:
http://docs.python.org/3.4/whatsnew/3.4.html
So, since the release of Python 3.4, the up-to-date way to install pip on Windows is to just install Python.

The recommended way to use it is to call it as a module, especially with multiple python distributions or versions installed, to guarantee packages go to the correct place:
python -m pip install --upgrade packageXYZ

https://docs.python.org/3/installing/#work-with-multiple-versions-of-python-installed-in-parallel


回答 5

当我必须使用Windows时,我使用ActivePython,它将自动将所有内容添加到您的PATH中,并包括一个名为PyPM的软件包管理器,该软件包管理器提供了二进制软件包管理,从而使安装软件包变得更快,更简单。

pipeasy_install不是完全一样的东西,所以有一些事情可以打通pip,但不是easy_install ,反之亦然

我的建议是您获得ActivePython社区版,不要担心在Windows上为Python设置所有东西的麻烦。然后,您可以使用pypm

如果要使用pip,则必须检查PyPMActiveState安装程序中的选项。安装后,您只需要注销并再次登录,pip即可在命令行中使用,因为它包含在ActiveState安装程序PyPM选项中,并且安装程序已经为您设置了路径。PyPM也可以使用,但您不必使用它。

When I have to use Windows, I use ActivePython, which automatically adds everything to your PATH and includes a package manager called PyPM which provides binary package management making it faster and simpler to install packages.

pip and easy_install aren’t exactly the same thing, so there are some things you can get through pip but not easy_install and vice versa.

My recommendation is that you get ActivePython Community Edition and don’t worry about the huge hassle of getting everything set up for Python on Windows. Then, you can just use pypm.

In case you want to use pip you have to check the PyPM option in the ActiveState installer. After installation you only need to logoff and log on again, and pip will be available on the commandline, because it is contained in the ActiveState installer PyPM option and the paths have been set by the installer for you already. PyPM will also be available, but you do not have to use it.


回答 6

最新的方法是使用Windows的软件包管理器Chocolatey

安装完成后,您所要做的就是打开命令提示符并运行下面的以下三个命令,这将安装Python 2.7,easy_install和pip。它会自动检测您是在x64还是x86 Windows上。

cinst python
cinst easy.install
cinst pip

Chocolatey Gallery上的所有其他Python软件包都可以在这里找到。

The up-to-date way is to use Windows’ package manager Chocolatey.

Once this is installed, all you have to do is open a command prompt and run the following the three commands below, which will install Python 2.7, easy_install and pip. It will automatically detect whether you’re on x64 or x86 Windows.

cinst python
cinst easy.install
cinst pip

All of the other Python packages on the Chocolatey Gallery can be found here.


回答 7

2015年3月更新

Python 2.7.9和更高版本(在Python 2系列上)以及Python 3.4和更高版本默认情况下都包含pip,因此您可能已经拥有pip。

如果不这样做,请在提示符下运行以下一行命令(可能需要管理员访问权限):

python -c "exec('try: from urllib2 import urlopen \nexcept: from urllib.request import urlopen');f=urlopen('https://bootstrap.pypa.io/get-pip.py').read();exec(f)"

它将安装pip。如果尚未安装Setuptoolsget-pip.py也将为您安装它。

如评论中所述,以上命令将从GitHub上的Pip源代码存储库下载代码,并在您的环境中动态运行它。因此请注意,这是下载,检查和运行步骤的快捷方式,所有这些操作都使用Python本身通过一个命令完成。如果您信任Pip,请毫无疑问地继续。

确保Windows环境变量PATH包含Python的文件夹(对于Python 2.7.x,默认安装:C:\Python27C:\Python27\Scripts,对于Python 3.3x:C:\Python33C:\Python33\Scripts,依此类推)。

Update March 2015

Python 2.7.9 and later (on the Python 2 series), and Python 3.4 and later include pip by default, so you may have pip already.

If you don’t, run this one line command on your prompt (which may require administrator access):

python -c "exec('try: from urllib2 import urlopen \nexcept: from urllib.request import urlopen');f=urlopen('https://bootstrap.pypa.io/get-pip.py').read();exec(f)"

It will install pip. If Setuptools is not already installed, get-pip.py will install it for you too.

As mentioned in comments, the above command will download code from the Pip source code repository at GitHub, and dynamically run it at your environment. So be noticed that this is a shortcut of the steps download, inspect and run, all with a single command using Python itself. If you trust Pip, proceed without doubt.

Be sure that your Windows environment variable PATH includes Python’s folders (for Python 2.7.x default install: C:\Python27 and C:\Python27\Scripts, for Python 3.3x: C:\Python33 and C:\Python33\Scripts, and so on).


回答 8

安装人员

我内置的Windows安装两种分发PIP这里(其目标是使用pip,而无需任何引导用easy_install或保存和运行Python脚本):

在Windows上,只需先下载并安装distribute,然后pip从上面的链接下载即可。distribute上面的链接确实包含存根.exe安装程序,并且当前仅32位。我尚未在64位Windows上测试过效果。

在Windows上构建

将其重做为新版本的过程并不困难,我将其包含在此处以供参考。

建造 distribute

为了获得存根.exe文件,您需要具有Visual C ++编译器(显然也可以与MinGW一起编译)

hg clone https://bitbucket.org/tarek/distribute
cd distribute
hg checkout 0.6.27
rem optionally, comment out tag_build and tag_svn_revision in setup.cfg
msvc-build-launcher.cmd
python setup.py bdist_win32
cd ..
echo build is in distribute\dist

建造 pip

git clone https://github.com/pypa/pip.git
cd pip
git checkout 1.1
python setup.py bdist_win32
cd ..
echo build is in pip\dist

Installers

I’ve built Windows installers for both distribute and pip here (the goal being to use pip without having to either bootstrap with easy_install or save and run Python scripts):

On Windows, simply download and install first distribute, then pip from the above links. The distribute link above does contain stub .exe installers, and these are currently 32-bit only. I haven’t tested the effect on 64-bit Windows.

Building on Windows

The process to redo this for new versions is not difficult, and I’ve included it here for reference.

Building distribute

In order to get the stub .exe files, you need to have a Visual C++ compiler (it is apparently compilable with MinGW as well)

hg clone https://bitbucket.org/tarek/distribute
cd distribute
hg checkout 0.6.27
rem optionally, comment out tag_build and tag_svn_revision in setup.cfg
msvc-build-launcher.cmd
python setup.py bdist_win32
cd ..
echo build is in distribute\dist

Building pip

git clone https://github.com/pypa/pip.git
cd pip
git checkout 1.1
python setup.py bdist_win32
cd ..
echo build is in pip\dist

回答 9

以下内容适用于Python 2.7。保存此脚本并启动它:

https:

//raw.github.com/pypa/pip/master/contrib/get-pip.py安装了Pip,然后将路径添加到您的环境:

C:\Python27\Scripts

最后

pip install virtualenv

另外,您还需要Microsoft Visual C ++ 2008 Express才能获得良好的编译器,并在安装软件包时避免出现此类消息:

error: Unable to find vcvarsall.bat

如果您使用的是Windows 7的64位版本,则可能会在64位Windows 7上阅读64位Python安装问题,以成功安装Python可执行程序包(带有注册表项)。

The following works for Python 2.7. Save this script and launch it:

https://raw.github.com/pypa/pip/master/contrib/get-pip.py

Pip is installed, then add the path to your environment :

C:\Python27\Scripts

Finally

pip install virtualenv

Also you need Microsoft Visual C++ 2008 Express to get the good compiler and avoid these kind of messages when installing packages:

error: Unable to find vcvarsall.bat

If you have a 64-bit version of Windows 7, you may read 64-bit Python installation issues on 64-bit Windows 7 to successfully install the Python executable package (issue with registry entries).


回答 10

对于最新的Python下载-我在Windows上安装了python 3.6。您不必怀疑所需的一切都在那里,请屏息,我将向您展示如何做到这一点。

  1. 确保为我安装python的位置在以下目录中

现在,如果您在Windows上,让我们将python和pip添加到环境变量路径设置中,以便在任何地方键入pip或python都可以从安装它们的地方调用python aor pip。

因此,在屏幕上方“ SCRIPTS ” 下的文件夹下找到PIP,让我们在环境变量路径中添加Python和PIP。

快完成了,让我们用CMD进行测试以使用pip安装goole软件包。

pip install google

再见!

For latest Python Download – I have python 3.6 on windows. You don’t have to wonder everything you need is there , take a breath i will show you how to do it.

  1. make sure where you install python for me its was in the following directory

Now , lets add python and pip into environment variable path settings if you are on windows, so that typing pip or python anywhere call python aor pip from where they are installed.

So, PIP is found under the folder in above screen “SCRIPTS” Lets add Python and PIP in environment variable path.

Almost Done , Let test with CMD to install goole package using pip.

pip install google

BYE BYE!


回答 11

要在Python 2.x上全局安装pip ,如Adrián所述,easy_install似乎是最好的解决方案。

但是pip 的安装说明建议使用virtualenv,因为每个virtualenv都会自动安装pip。这不需要root用户访问权限或修改系统Python安装。

尽管安装virtualenv仍然需要easy_install。

2018更新:

Python 3.3+现在包含venv模块,可轻松创建虚拟环境,如下所示:

python3 -m venv /path/to/new/virtual/environment

请参阅有关在创建后激活环境的不同平台方法的文档,但通常为以下之一:

$ source <venv>/bin/activate 

C:\> <venv>\Scripts\activate.bat

To install pip globally on Python 2.x, easy_install appears to be the best solution as Adrián states.

However the installation instructions for pip recommend using virtualenv since every virtualenv has pip installed in it automatically. This does not require root access or modify your system Python installation.

Installing virtualenv still requires easy_install though.

2018 update:

Python 3.3+ now includes the venv module for easily creating virtual environments like so:

python3 -m venv /path/to/new/virtual/environment

See documentation for different platform methods of activating the environment after creation, but typically one of:

$ source <venv>/bin/activate 

C:\> <venv>\Scripts\activate.bat

回答 12

要使用pip,并不一定需要直接在系统中安装pip。您可以通过使用它virtualenv。您可以按照以下步骤操作:

我们通常需要为一个特定项目安装Python软件包。因此,现在创建一个项目文件夹,比方说myproject。

  • 从的解压缩文件夹中复制virtualenv.py文件virtualenv,并将其粘贴到myproject文件夹中

现在创建一个虚拟环境,在myproject文件夹中,如下所示说myvirtualenv

python virtualenv.py myvirtualenv

它会向您显示:

New python executable in myvirtualenv\Scripts\python.exe
Installing setuptools....................................done.
Installing pip.........................done.

现在,您的虚拟环境myvirtualenv已在项目文件夹中创建。您可能会注意到,pip现在已安装在您的虚拟环境中。您需要做的就是使用以下命令激活虚拟环境。

myvirtualenv\Scripts\activate

您将在命令提示符下看到以下内容:

(myvirtualenv) PATH\TO\YOUR\PROJECT\FOLDER>pip install package_name

现在,您可以开始使用pip,但是请确保已激活虚拟环境,方法是查看提示左侧的内容。

这是在虚拟环境中安装pip的最简单方法之一,但是您需要随身携带virtualenv.py文件。

有关安装pip / virtualenv / virtualenvwrapper的更多方法,请访问thegauraw.tumblr.com

To use pip, it is not mandatory that you need to install pip in the system directly. You can use it through virtualenv. What you can do is follow these steps:

We normally need to install Python packages for one particular project. So, now create a project folder, let’s say myproject.

  • Copy the virtualenv.py file from the decompressed folder of virtualenv, and paste inside the myproject folder

Now create a virtual environment, let’s say myvirtualenv as follows, inside the myproject folder:

python virtualenv.py myvirtualenv

It will show you:

New python executable in myvirtualenv\Scripts\python.exe
Installing setuptools....................................done.
Installing pip.........................done.

Now your virtual environment, myvirtualenv, is created inside your project folder. You might notice, pip is now installed inside you virtual environment. All you need to do is activate the virtual environment with the following command.

myvirtualenv\Scripts\activate

You will see the following at the command prompt:

(myvirtualenv) PATH\TO\YOUR\PROJECT\FOLDER>pip install package_name

Now you can start using pip, but make sure you have activated the virtualenv looking at the left of your prompt.

This is one of the easiest way to install pip i.e. inside virtual environment, but you need to have virtualenv.py file with you.

For more ways to install pip/virtualenv/virtualenvwrapper, you can refer to thegauraw.tumblr.com.


回答 13

我只是想为那些无法从Windows 64位安装setuptools的用户添加一个解决方案。在python.org上的此错误中讨论了该问题,截至本评论发布之日仍未解决。提到了一个简单的解决方法,它可以完美地工作。一次注册表更改对我来说很成功。

链接:http//bugs.python.org/issue6792#

适用于我的解决方案…:

为2.6+版本的Python添加此注册表设置:

 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath]
 @="C:\\Python26\\"

这很可能是您在Python 2.6+中已经拥有的注册表设置:

 [HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
 @="C:\\Python26\\"

显然,您将需要用正在运行的Python版本替换2.6版本。

I just wanted to add one more solution for those having issues installing setuptools from Windows 64-bit. The issue is discussed in this bug on python.org and is still unresolved as of the date of this comment. A simple workaround is mentioned and it works flawlessly. One registry change did the trick for me.

Link: http://bugs.python.org/issue6792#

Solution that worked for me…:

Add this registry setting for 2.6+ versions of Python:

 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath]
 @="C:\\Python26\\"

This is most likely the registry setting you will already have for Python 2.6+:

 [HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
 @="C:\\Python26\\"

Clearly, you will need to replace the 2.6 version with whatever version of Python you are running.


回答 14

更新于2016年: Pip应该已经包含在中Python 2.7.9+ or 3.4+,但是如果由于某种原因它不存在,则可以使用以下一种格式。

PS:

  1. 在大多数情况下,这已经可以满足要求,但是,如果有必要,请确保环境变量PATH包含Python的文件夹(例如,Python 2.7.x在Windows默认安装:C:\Python27 and C:\Python27\Scripts,for Python 3.3xC:\Python33 and C:\Python33\Scripts等)

  2. 我遇到同样的问题,然后在这里的官方网站上找到了这种最简单的方法(一行代码!): http //www.pip-installer.org/en/latest/installing.html

不敢相信那里有这么长的答案(也许已经过时了?)。对他们表示感谢,但请对这个简短的答案进行投票,以帮助更多的新手!

Updated at 2016 : Pip should already be included in Python 2.7.9+ or 3.4+, but if for whatever reason it is not there, you can use the following one-liner.

PS:

  1. This should already be satisfied in most cases but, if necessary, be sure that your environment variable PATH includes Python’s folders (for example, Python 2.7.x on Windows default install: C:\Python27 and C:\Python27\Scripts, for Python 3.3x: C:\Python33 and C:\Python33\Scripts, etc)

  2. I encounter same problem and then found such perhaps easiest way (one liner!) mentioned on official website here: http://www.pip-installer.org/en/latest/installing.html

Can’t believe there are so many lengthy (perhaps outdated?) answers out there. Feeling thankful to them but, please up-vote this short answer to help more new comers!


回答 15

到目前为止,我发现的最好方法就是两行代码:

curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

它已在Windows 8上使用PowerShell,Cmd和Git Bash(MinGW)进行了测试。

您可能想要将路径添加到您的环境。就像C:\Python33\Scripts

The best way I found so far, is just two lines of code:

curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

It was tested on Windows 8 with PowerShell, Cmd, and Git Bash (MinGW).

And you probably want to add the path to your environment. It’s somewhere like C:\Python33\Scripts.


回答 16

在这里,如何通过简单的方法安装pip。

  1. 这些内容复制并粘贴为get-pip.py文件
  2. get-pip.py复制并粘贴到python文件夹中。C:\Python27
  3. 双击获取get-pip.py文件,它将pip安装到您的计算机上。
  4. 现在您必须为C:\Python27\Scripts环境变量添加路径,因为它包含pip.exe文件。
  5. 现在您可以使用点子了。打开cmd并键入为
    pip install package_name

Here how to install pip with easy way.

  1. copy and paste these content in a file as get-pip.py
  2. copy and paste get-pip.py into python folder.C:\Python27
  3. Double click to get-pip.py file.it will install pip to your computer.
  4. Now you have to add C:\Python27\Scripts path to your enviroment variable.Because it includes pip.exe file.
  5. Now you are ready to use pip. Open cmd and type as
    pip install package_name

回答 17

PythonXY带有pip包括,除其他

PythonXY comes with pip included, among others.


回答 18

我在Windows上使用来自continuum.io 的跨平台Anaconda软件包管理器,它是可靠的。它具有虚拟环境管理功能以及具有常用功能(例如conda,pip)的功能齐全的外壳。

> conda install <package>               # access distributed binaries

> pip install <package>                 # access PyPI packages 

conda还附带了具有非Python依赖项(例如pandasnumpy等)的库的二进制文件。这在Windows上特别有用,因为可能很难正确编译C依赖项。

I use the cross-platform Anaconda package manager from continuum.io on Windows and it is reliable. It has virtual environment management and a fully featured shell with common utilities (e.g. conda, pip).

> conda install <package>               # access distributed binaries

> pip install <package>                 # access PyPI packages 

conda also comes with binaries for libraries with non-Python dependencies, e.g. pandas, numpy, etc. This proves useful particularly on Windows as it can be hard to correctly compile C dependencies.


回答 19

按照此处的说明进行安装时,我遇到了一些问题。我认为以相同的方式在每个Windows环境中安装非常棘手。就我而言,出于同一目的,我需要在同一台计算机上使用Python 2.6、2.7和3.3,这就是为什么我认为还有更多问题的原因。但是以下说明对我来说非常有效,因此可能要根据您的环境尝试使用此说明:

http://docs.python-guide.org/zh-CN/latest/starting/install/win/

另外,由于不同的环境,我发现使用虚拟环境非常有用,我的网站使用不同的库,最好将它们封装到一个文件夹中,查看说明,如果已安装PIP,则只需安装VirtualEnv:

pip install virtualenv

将所有文件运行到该文件夹​​中

virtualenv venv

几秒钟后,您将在venv文件夹中拥有一个包含所有内容的虚拟环境,要运行它,请运行venv / Scripts / activate.bat(停用环境很容易,请使用deactivate.bat)。您安装的每个库都将以venv \ Lib \ site-packages结尾,并且很容易将整个环境移动到某个地方。

我发现的唯一缺点是某些代码编辑器无法识别这种环境,并且由于未找到导入的库,因此您会在代码中看到警告。当然,有一些棘手的方法可以做到这一点,但编辑人员切记,虚拟环境如今非常普遍。

希望能帮助到你。

I had some issues installing in different ways when I followed instructions here. I think it’s very tricky to install in every Windows environment in the same way. In my case I need Python 2.6, 2.7 and 3.3 in the same machine for different purposes so that’s why I think there’re more problems. But the following instructions worked perfectly for me, so might be depending on your environment you should try this one:

http://docs.python-guide.org/en/latest/starting/install/win/

Also, due to the different environments I found incredible useful to use Virtual Environments, I had websites that use different libraries and it’s much better to encapsulate them into a single folder, check out the instructions, briefly if PIP is installed you just install VirtualEnv:

pip install virtualenv

Into the folder you have all your files run

virtualenv venv

And seconds later you have a virtual environment with everything in venv folder, to activate it run venv/Scripts/activate.bat (deactivate the environment is easy, use deactivate.bat). Every library you install will end up in venv\Lib\site-packages and it’s easy to move your whole environment somewhere.

The only downside I found is some code editors can’t recognize this kind of environments, and you will see warnings in your code because imported libraries are not found. Of course there’re tricky ways to do it but it would be nice editors keep in mind Virtual Environments are very normal nowadays.

Hope it helps.


回答 20

  1. 下载脚本:https : //raw.github.com/pypa/pip/master/contrib/get-pip.py
  2. 将其保存在驱动器上,例如C:\ pip-script \ get-pip.py
  3. 从命令提示符导航到该路径,然后运行“ python get-pip.py”

指南链接:http : //www.pip-installer.org/en/latest/installing.html#install-pip

注意:请确保还将这样的脚本路径(C:\ Python27 \ Scripts)添加到int%PATH%环境变量中。

  1. Download script: https://raw.github.com/pypa/pip/master/contrib/get-pip.py
  2. Save it on drive somewhere like C:\pip-script\get-pip.py
  3. Navigate to that path from command prompt and run ” python get-pip.py “

Guide link: http://www.pip-installer.org/en/latest/installing.html#install-pip

Note: Make sure scripts path like this (C:\Python27\Scripts) is added int %PATH% environment variable as well.


回答 21

很简单:

Step 1: wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
Step 2: wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
Step 2: python ez_setup.py
Step 3: python get-pip.py

(确保您的Python和Python脚本目录(例如C:\Python27C:\Python27\Scripts)在PATH中。)

It’s very simple:

Step 1: wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
Step 2: wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
Step 2: python ez_setup.py
Step 3: python get-pip.py

(Make sure your Python and Python script directory (for example, C:\Python27 and C:\Python27\Scripts) are in the PATH.)


回答 22

从2014年2月4日开始工作:):

如果您按照@Colonel Panic的建议尝试通过Windows安装程序文件从http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip安装pip ,则可能已成功安装了pip软件包管理器,但是您可能无法使用pip安装任何软件包。如果您查看pip.log文件,您可能还会遇到与尝试安装Beautiful Soup 4时遇到的SSL错误相同的错误:

Downloading/unpacking beautifulsoup4
  Getting page https://pypi.python.org/simple/beautifulsoup4/
  Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
  Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4

问题是OpenSSL的旧版本与pip 1.3.1及更高版本不兼容。目前,最简单的解决方法是安装不需要SSL的 pip 1.2.1

在Windows上安装Pip:

  1. https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz下载pip 1.2.1
  2. 提取pip-1.2.1.tar.gz文件
  3. 将目录更改为提取的文件夹: cd <path to extracted folder>/pip-1.2.1
  4. python setup.py install
  5. 现在确保C:\Python27\Scripts位于PATH中,因为pip安装在C:\Python27\Scripts目录中,这与C:\Python27\Lib\site-packages通常安装Python软件包的位置不同

现在尝试使用pip安装任何软件包。

例如,要requests使用pip 安装软件包,请从cmd运行此命令:

pip install requests

哇!requests将成功安装,您将收到一条成功消息。

Working as of Feb 04 2014 :):

If you have tried installing pip through the Windows installer file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip as suggested by @Colonel Panic, you might have installed the pip package manager successfully, but you might be unable to install any packages with pip. You might also have got the same SSL error as I got when I tried to install Beautiful Soup 4 if you look in the pip.log file:

Downloading/unpacking beautifulsoup4
  Getting page https://pypi.python.org/simple/beautifulsoup4/
  Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
  Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4

The problem is an issue with an old version of OpenSSL being incompatible with pip 1.3.1 and above versions. The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

Installing Pip on Windows:

  1. Download pip 1.2.1 from https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
  2. Extract the pip-1.2.1.tar.gz file
  3. Change directory to the extracted folder: cd <path to extracted folder>/pip-1.2.1
  4. Run python setup.py install
  5. Now make sure C:\Python27\Scripts is in PATH because pip is installed in the C:\Python27\Scripts directory unlike C:\Python27\Lib\site-packages where Python packages are normally installed

Now try to install any package using pip.

For example, to install the requests package using pip, run this from cmd:

pip install requests

Whola! requests will be successfully installed and you will get a success message.


回答 23

如果您使用的是从python.org下载的Python 2> = 2.7.9或Python 3> = 3.4二进制文件,则已经安装了pip,但是您需要升级pip。

在Windows上可以轻松完成升级

转到Python命令行并在Python命令下运行

python -m pip install -U pip

使用get-pip.py安装

get-pip.py下载到同一文件夹或您选择的任何其他文件夹中。我假设您将从python.exe文件将其下载到同一文件夹中,然后运行此命令

python get-pip.py

Pip的安装指南非常干净和简单。

使用此工具,您应该可以在两分钟内开始使用Pip。

pip is already installed if you’re using Python 2 >=2.7.9 or Python 3 >=3.4 binaries downloaded from python.org, but you’ll need to upgrade pip.

On Windows upgrade can be done easily

Go to Python command line and run below Python command

python -m pip install -U pip

Installing with get-pip.py

Download get-pip.py in the same folder or any other folder of your choice. I am assuming you will download it in the same folder from you have python.exe file and run this command

python get-pip.py

Pip’s installation guide is pretty clean and simple.

Using this you should be able to get started with Pip in under two minutes.


回答 24

如果您甚至对pip版本有其他问题,可以尝试一下

pip install --trusted-host pypi.python.org --upgrade pip

if you even have other problems with pip version you can try this

pip install --trusted-host pypi.python.org --upgrade pip

回答 25

简单的CMD方法

使用CURL下载get-pip.py

curl --http1.1 https://bootstrap.pypa.io/get-pip.py --output get-pip.py

执行下载的python文件

python get-pip.py

然后将C:\Python37\Scripts路径添加到您的环境变量。假设Python37您的C盘中有一个文件夹,该文件夹的名称可能会因安装的python版本而异

现在,您可以通过运行来安装python软件包

pip install awesome_package_name

Simple CMD way

Use CURL to download get-pip.py

curl --http1.1 https://bootstrap.pypa.io/get-pip.py --output get-pip.py

Execute downloaded python file

python get-pip.py

Then add C:\Python37\Scripts path to your environment variable. Assumes that there is a Python37 folder in your C drive, that folder name may varied according to the installed python version

Now you can install python packages by running

pip install awesome_package_name

回答 26

Python2和安装PipPython3

  1. get-pip.py下载到计算机上的文件夹。
  2. 打开命令提示符,然后导航到包含的文件夹get-pip.py
  3. 运行以下命令:python get-pip.pypython3 get-pip.pypython3.6 get-pip.py,取决于哪个版本的python要安装pip
  4. 点现在应该安装了!

旧答案(仍然有效)

你有没有尝试过 ?

python -m ensurepip

这可能是在任何系统上安装pip的最简单方法。

Installing Pip for Python2 and Python3

  1. Download get-pip.py to a folder on your computer.
  2. Open a command prompt and navigate to the folder containing get-pip.py.
  3. Run the following command:python get-pip.py, python3 get-pip.py or python3.6 get-pip.py, depending on which version of python you want to install pip
  4. Pip should be now installed!

Old answer (still valid)

Have you tried ?

python -m ensurepip

it’s probably the easiest to install pip on any system.


回答 27

只需从此处https://pypi.python.org/pypi/setuptools#windows-simplified下载setuptools-15.2.zip(md5),然后运行ez_setup.py。

Just download setuptools-15.2.zip (md5), from here https://pypi.python.org/pypi/setuptools#windows-simplified , and run ez_setup.py.


回答 28

或者,您可以获得pip-Win,它是pip的多合一安装程序,并且virtualenv在Windows及其GUI上。

  • 从一个Python解释器(即版本)切换到另一个(包括py和pypy)
  • 查看所有已安装的软件包,以及它们是否为最新
  • 安装或升级软件包,或升级pip本身
  • 创建和删除虚拟环境,并在它们之间切换
  • 使用选定的解释器运行IDLE或其他Python脚本

Alternatively, you can get pip-Win which is an all-in-one installer for pip and virtualenv on Windows and its GUI.

  • Switch from one Python interpreter (i.e. version) to another (including py and pypy)
  • See all installed packages, and whether they are up-to-date
  • Install or upgrade a package, or upgrade pip itself
  • Create and delete virtual environments, and switch between them
  • Run the IDLE or another Python script, with the selected interpreter

回答 29

现在,它与Python捆绑在一起。您不需要安装它。

pip -V

这样可以检查是否已安装pip。在极少数情况下,如果未安装,请下载get-pip.py文件并使用python作为

python get-pip.py

Now, it is bundled with Python. You don’t need to install it.

pip -V

This is how you can check whether pip is installed or not. In rare case, if it is not installed, download get-pip.py file and run it with python as

python get-pip.py

Pipenv-面向人类的Python开发工作流

Pipenv 是一个旨在带来最好的包装世界的工具(捆扎师、作曲家、NPM、货物、纱线等)来到Python世界在我们的世界里,Windows是一等公民

它会自动为您的项目创建和管理一个虚拟环境,并在您的Pipfile当您安装/卸载软件包时。它还产生了非常重要的Pipfile.lock,它用于生成确定性构建。

Pipenv寻求解决的问题是多方面的:

  • 您不再需要使用pipvirtualenv分开的。他们一起工作
  • 管理requirements.txt文件can be
    problematic
    ,因此Pipenv使用即将到来的PipfilePipfile.lock取而代之的是,对于基本用例,哪个更优越
  • 散列总是在任何地方使用。保安。自动暴露安全漏洞
  • 让您深入了解依赖关系图(例如$ pipenv graph)
  • 通过加载简化开发工作流.env文件

您可以在浏览器中快速播放Pipenv:

安装

如果您使用的是Debian Buster+:

$ sudo apt install pipenv

或者,如果您使用的是Fedora:

$ sudo dnf install pipenv

或者,如果您使用的是FreeBSD:

# pkg install py36-pipenv

或者,如果您使用的是Windows:

# pip install --user pipenv

当以上选项都不存在时,建议使用Pipx

$ pipx install pipenv

否则,请参阅documentation有关说明,请参阅

✨🍰✨

☤用户表彰

大卫·刚(David Gang)

这个包管理器真的很棒。这是我第一次确切地知道我安装的依赖项是什么,以及可传递依赖项是什么。再加上安装是确定性的这一事实,使得这个包管理器像货物一样是一流的

贾斯汀·迈尔斯·福尔摩斯

Pipenv最终是一种抽象,其目的是让头脑参与进来,而不仅仅是文件系统

☤功能

  • 真正实现确定性构建,同时轻松指定只有你想要的
  • 生成并检查锁定依赖项的文件哈希
  • 自动安装所需的Python,如果pyenv有空房吗?
  • 自动递归地查找您的项目主目录,方法是查找Pipfile
  • 自动生成一个Pipfile,如果不存在
  • 自动在标准位置创建一个Virtualenv
  • 自动将包添加/删除到Pipfile卸载/安装它们时
  • 自动加载.env文件(如果存在)

主要命令有installuninstall,以及lock,它会生成一个Pipfile.lock这些都是用来取代$ pip install用法以及手动虚拟环境管理(要激活虚拟环境,请运行$ pipenv shell)

基本概念

  • 当虚拟环境不存在时,将自动创建一个虚拟环境
  • 当没有参数传递给install,所有套餐[packages]将安装指定的
  • 要初始化Python 3虚拟环境,请运行$ pipenv --three
  • 要初始化Python 2虚拟环境,请运行$ pipenv --two
  • 否则,无论viralenv缺省值是什么,都将是缺省值

其他命令

  • shell将在激活了viralenv的情况下生成一个shell
  • run将运行来自Virtualenv的给定命令,并转发任何参数(例如$ pipenv run python)
  • check断言当前环境满足PEP 508要求
  • graph将打印所有已安装依赖项的漂亮图表

外壳完井

例如,对于鱼,把这个放在你的~/.config/fish/completions/pipenv.fish

eval (pipenv --completion)

或者,使用bash,将此内容放入您的.bashrc.bash_profile

eval "$(pipenv --completion)"

魔术外壳完成现已启用!还有一个fish
plugin
,它将自动为您激活您的子壳!

鱼是最好的贝壳。你应该用它

☤使用率

$ pipenv
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

Options:
  --where          Output project home information.
  --venv           Output virtualenv information.
  --py             Output Python interpreter information.
  --envs           Output Environment Variable options.
  --rm             Remove the virtualenv.
  --bare           Minimal output.
  --completion     Output completion (to be eval'd).
  --man            Display manpage.
  --three / --two  Use Python 3/2 when creating virtualenv.
  --python TEXT    Specify which version of Python virtualenv should use.
  --site-packages  Enable site-packages for the virtualenv.
  --version        Show the version and exit.
  -h, --help       Show this message and exit.


Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check      Checks for security vulnerabilities and against PEP 508 markers
             provided in Pipfile.
  clean      Uninstalls all packages not specified in Pipfile.lock.
  graph      Displays currently–installed dependency graph information.
  install    Installs provided packages and adds them to Pipfile, or (if no
             packages are given), installs all packages from Pipfile.
  lock       Generates Pipfile.lock.
  open       View a given module in your editor.
  run        Spawns a command installed into the virtualenv.
  scripts    Displays the shortcuts in the (optional) [scripts] section of 
             Pipfile. 
  shell      Spawns a shell within the virtualenv.
  sync       Installs all packages specified in Pipfile.lock.
  uninstall  Un-installs a provided package and removes it from Pipfile.

找到项目:

$ pipenv --where
/Users/kennethreitz/Library/Mobile Documents/com~apple~CloudDocs/repos/kr/pipenv/test

找到Virtualenv:

$ pipenv --venv
/Users/kennethreitz/.local/share/virtualenvs/test-Skyy4vre

找到Python解释器:

$ pipenv --py
/Users/kennethreitz/.local/share/virtualenvs/test-Skyy4vre/bin/python

安装软件包:

$ pipenv install
Creating a virtualenv for this project...
...
No package provided, installing all dependencies.
Virtualenv location: /Users/kennethreitz/.local/share/virtualenvs/test-EJkjoYts
Installing dependencies from Pipfile.lock...
...

To activate this project's virtualenv, run the following:
$ pipenv shell

从GIT安装:

您可以使用按照以下规则格式化的URL从GIT和其他版本控制系统安装带有Pipenv的软件包:

<vcs_type>+<scheme>://<location>/<user_or_organization>/<repository>@<branch_or_tag>#<package_name>

唯一可选的部分是@<branch_or_tag>部分。在SSH上使用GIT时,您可以使用速记VC和方案别名git+git@<location>:<user_or_organization>/<repository>@<branch_or_tag>#<package_name>请注意,这将被转换为git+ssh://git@<location>在解析时

的有效值<vcs_type>包括gitbzrsvn,以及hg的有效值<scheme>包括http,httpsssh,以及file在特定情况下,您还可以访问其他方案:svn可以与svn作为一个计划,并且bzr可以与sftplp

请注意,它是强烈推荐在可编辑模式下安装任何受版本控制的依赖项,请使用pipenv install -e,以确保每次执行依赖项解析时都可以使用存储库的最新副本执行依赖项解析,并确保它包括所有已知的依赖项

以下是安装位于以下位置的git存储库的用法示例https://github.com/requests/requests.gitFrom标签v2.19.1作为包名称requests

$ pipenv install -e git+https://github.com/requests/requests.git@v2.19#egg=requests
Creating a Pipfile for this project...
Installing -e git+https://github.com/requests/requests.git@v2.19.1#egg=requests...
[...snipped...]
Adding -e git+https://github.com/requests/requests.git@v2.19.1#egg=requests to Pipfile's [packages]...
[...]

您可以阅读更多关于pip’s implementation of vcs support here

安装开发依赖项:

$ pipenv install pytest --dev
Installing pytest...
...
Adding pytest to Pipfile's [dev-packages]...

显示依赖关系图:

$ pipenv graph
requests==2.18.4
  - certifi [required: >=2017.4.17, installed: 2017.7.27.1]
  - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4]
  - idna [required: >=2.5,<2.7, installed: 2.6]
  - urllib3 [required: <1.23,>=1.21.1, installed: 1.22]

生成锁定文件:

$ pipenv lock
Assuring all dependencies from Pipfile are installed...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Note: your project now has only default [packages] installed.
To install [dev-packages], run: $ pipenv install --dev

安装所有开发人员依赖项:

$ pipenv install --dev
Pipfile found at /Users/kennethreitz/repos/kr/pip2/test/Pipfile. Considering this to be the project home.
Pipfile.lock out of date, updating...
Assuring all dependencies from Pipfile are installed...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...

卸载所有内容:

$ pipenv uninstall --all
No package provided, un-installing all dependencies.
Found 25 installed package(s), purging...
...
Environment now purged and fresh!

使用外壳:

$ pipenv shell
Loading .env environment variables...
Launching subshell in virtual environment. Type 'exit' or 'Ctrl+D' to return.
$ ▯

☤文档

文档位于pipenv.pypa.io

整理的关于 pip 的 15 个使用小技巧

 

本文转载自公众号【 Python大数据分析】

认识pip

众所周知,pip可以对python的第三方库进行安装、更新、卸载等操作,十分方便。

pip的全称:package installer for python,也就是Python包管理工具。

可能有些人用了很久pip,但还不清楚包管理工具是个啥。

我们先从Python这门语言说起,Python之所以受欢迎不光是因为它简单易学,更重要的是它有成千上万的宝藏库。

这些库相当于是已经集成好的工具,只要安装就能在Python里使用。它们可以处理各式各样的问题,无需你再造轮子,而且随着社区的不断更新维护,有些库越来越强大,几乎能媲美企业级应用。

那么这些工具库怎么下载安装呢?它们被放在一个统一的“仓库”里,名叫PyPi(Python Package Index),所有的库安装都是从这里调度。

有了仓库之后,还需要有管理员,pip就是这样一个角色。pip把库从PyPi取出来,然后安装到Python里,还可以管理安装好的库,比如更新、查看、搜索、卸载等等。

总的来说,pip的Python第三方库的大管家,搞懂它,会让你省很多事。

下面总结了30个pip使用过程中的常识和技巧,供大家参考。

「注:因为pip是一个命令行程序,所以pip一般都在命令行中执行各种操作」

1、安装pip

从Python 3.4开始,pip已经内置在Python中,所以无需再次安装。

如果你的Python版本没有pip,那可以使用下面两种方法安装。

(1) 命令行中输入easy_install pip,非常快捷

(2) 在下面网址中下载pip安装文件,然后解压到python scripts目录中,执行python setup.py install安装即可

下载网址:https://pypi.org/project/pip/#files

下载文件:

2、查看pip版本

pip --version

3、升级pip

如果pip的版本太低,可以升级当前版本
pip install --upgrade pip

4、获取帮助

想了解如何使用pip,以及pip有哪些功能,执行下面语句可以获取详细教程:
pip help

5、安装库

使用pip安装第三方库,执行下面语句
pip install package_name

指定package版本:
pip install package_name==1.1.2

比如说,我要安装3.4.1版本的matplotlib
pip install matplotlib==3.4.1

6、批量安装库

如果一个项目需要安装很多库,那可以批量安装:
pip install -r e:\\requirements.txt

requirements.txt文件内容格式如下:

7、使用wheel文件安装库

这种方法适合离线安装,wheel文件是库的源文件,可以下载后放到本地安装。

步骤如下:

(1) 在下面网站里找相应库的.whl文件
https://www.lfd.uci.edu/~gohlke/pythonlibs/

(2) 下载.whl文件,注意对应的版本

(3) 在.whl所在文件夹内,按Shift键+鼠标右键,打开CMD窗口或者PowerShell

(4) 输入命令:
pip install matplotlib‑3.4.1‑cp39‑cp39‑win_amd64.whl
即可完成安装

8、卸载库

安装好的库可以再卸载:
pip uninstall package_name

9、升级库

对当前库进行版本升级:
pip install --upgrade package_name

10、查看库信息

pip show -f package_name

11、查看已安装的库

列出所有已安装的第三方库和对应版本
pip list

12、将库列表保存到指定文件中

把已经安装的库信息保存到到本地txt文件中:
pip freeze > requirements.txt

13、查看需要升级的库

目前已经安装的库中,看哪些需要版本升级
pip list -o

14、检查兼容问题

验证已安装的库是否有兼容依赖问题
pip check package-name

15、下载库到本地

将库下载到本地指定文件,保存为whl格式
pip download package_name -d "要保存的文件路径"

附:更换pip源

很多人抱怨pip安装库有些时候太慢了,那是pip源的问题。

前面说过pip从PyPi中下载库文件,但由于PyPi服务器在国外,访问起来很慢。

但国内提供了很多镜像源,用来替代PyPi,像清华源、豆瓣源、阿里云源等。

这些镜像源备份了PyPi里的数据,由于服务器在国内,速度会快很多。

但镜像源数据有滞后性,比如说清华源的pypi 镜像每 5 分钟同步一次。

使用镜像源有两种方式,以清华源为例:

(1) 临时使用

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package matplotlib

除了matplotlib是要安装的库名外,其他都是固定格式

(2) 设为默认

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

设为默认后,以后安装库都是从清华源下载,而且无需再加镜像源网址

附主流镜像源地址

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!

给作者打赏,选择打赏金额
¥1¥5¥10¥20¥50¥100¥200 自定义

​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典