标签归档:setuptools

“ pip install –editable ./” vs“ python setup.py开发”

问题:“ pip install –editable ./” vs“ python setup.py开发”

两者之间有什么明显区别

pip install -e /path/to/mypackage

和setuptools的变体?

python /path/to/mypackage/setup.py develop

Is there any significant difference between

pip install -e /path/to/mypackage

and the setuptools variant?

python /path/to/mypackage/setup.py develop

回答 0

尝试避免setup.py直接调用,它不会正确告诉pip您已安装软件包。

pip install -e

对于本地项目,相对于项目路径创建“ SomeProject.egg-info”目录。与仅使用相比setup.py develop,这是一个优势 ,它可以直接相对于当前工作目录创建“ egg-info”。

更多:文档

另请阅读setuptools的文档

Try to avoid calling setup.py directly, it will not properly tell pip that you’ve installed your package.

With pip install -e:

For local projects, the “SomeProject.egg-info” directory is created relative to the project path. This is one advantage over just using setup.py develop, which creates the “egg-info” directly relative the current working directory.

More: docs

Also read the setuptools’ docs.


为Python安装pip,virtualenv和分发的正确方法是什么?

问题:为Python安装pip,virtualenv和分发的正确方法是什么?

简短问题

背景

4314376问题的回答中,我建议使用,ez_setup以便随后进行安装pipvirtualenv如下所示:

curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

我最初是从Jesse Noller的博客文章中删除这些说明的,所以您想在Mac上使用Python吗?。我喜欢保持干净的全局site-packages目录的想法,因此我安装的唯一其他软件包是 virtualenvwrapperand distribute。(distribute由于此Python公共服务公告,我最近添加到了我的工具箱中。要安装这两个软件包,我使用了:

sudo pip install virtualenvwrapper
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

没有更多的设置工具和easy_install

要真正遵循该Python公共服务声明,在全新安装的Python上,请执行以下操作:

curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

雕文的斥责

在对SO问题4314376的回答的评论中,SO用户Glyph说:

没有。永远不要做sudo python setup.py install任何事情。编写〜/ .pydistutils.cfg,将您的pip安装放入〜/ .local或其他内容。特别是命名为的文件ez_setup.py往往会吸收诸如setuptools和easy_install之类的较新版本,这可能会破坏操作系统上的其他内容。

回到简短的问题

因此,Glyph的回答使我想到了最初的问题:

Short Question

Background

In my answer to SO question 4314376, I recommended using ez_setup so that you could then install pip and virtualenv as follows:

curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

I originally pulled these instructions from Jesse Noller’s blog post So you want to use Python on the Mac?. I like the idea of keeping a clean global site-packages directory, so the only other packages I install there are virtualenvwrapper and distribute. (I recently added distribute to my toolbox because of this Python public service announcement. To install these two packages, I used:

sudo pip install virtualenvwrapper
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

No more setuptools and easy_install

To really follow that Python public service announcement, on a fresh Python install, I would do the following:

curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

Glyph’s Rebuke

In a comment to my answer to SO question 4314376, SO user Glyph stated:

NO. NEVER EVER do sudo python setup.py install whatever. Write a ~/.pydistutils.cfg that puts your pip installation into ~/.local or something. Especially files named ez_setup.py tend to suck down newer versions of things like setuptools and easy_install, which can potentially break other things on your operating system.

Back to the short question

So Glyph’s response leads me to my original question:


回答 0

您可以执行此操作而无需在python本身中安装任何东西

您不需要sudo或任何特权。

您无需编辑任何文件。

将virtualenv安装到引导虚拟环境中。使用该虚拟环境创建更多内容。由于virtualenv附带了pip和分发,因此您一次安装即可获得所有内容。

  1. 下载virtualenv:
  2. 解压源压缩包
  3. 使用解压缩的tarball创建干净的虚拟环境。该虚拟环境将用于“引导”其他环境。您的所有虚拟环境将自动包含pip和分发。
  4. 使用pip将virtualenv安装到该引导环境中。
  5. 使用该引导环境创建更多内容!

这是bash中的一个示例:

# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

现在,您可以使用“引导”环境创建更多内容:

# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

发疯!

注意

假设您没有使用过旧的virtualenv版本。旧版本需要标记--no-site-packges(并取决于Python的版本--distribute)。现在,您可以使用just python virtualenv.py path-to-bootstrap或来创建引导环境python3 virtualenv.py path-to-bootstrap

You can do this without installing anything into python itself.

You don’t need sudo or any privileges.

You don’t need to edit any files.

Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything from one install.

  1. Download virtualenv:
  2. Unpack the source tarball
  3. Use the unpacked tarball to create a clean virtual environment. This virtual environment will be used to “bootstrap” others. All of your virtual environments will automatically contain pip and distribute.
  4. Using pip, install virtualenv into that bootstrap environment.
  5. Use that bootstrap environment to create more!

Here is an example in bash:

# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

Now you can use your “bootstrap” environment to create more:

# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

Go nuts!

Note

This assumes you are not using a really old version of virtualenv. Old versions required the flags --no-site-packges (and depending on the version of Python, --distribute). Now you can create your bootstrap environment with just python virtualenv.py path-to-bootstrap or python3 virtualenv.py path-to-bootstrap.


回答 1

我认为Glyph的意思是这样的:

  1. 创建目录~/.local(如果尚不存在)。
  2. 在你的~/.bashrc,保证~/.local/binPATH~/.localPYTHONPATH
  3. 创建一个~/.pydistutils.cfg包含以下内容的文件

    [install]
    prefix=~/.local

    这是一个标准的ConfigParser格式文件。

  4. 下载 distribute_setup.py并运行python distribute_setup.py(否sudo)。如果它抱怨site-packages目录不存在,请手动创建它:

    mkdir -p〜/ .local / lib / python2.7 / site-packages /

  5. 运行which easy_install以验证它来自~/.local/bin

  6. pip install virtualenv
  7. pip install virtualenvwrapper
  8. 创建一个包含文件夹的虚拟环境,例如 ~/.virtualenvs
  9. ~/.bashrc添加

    export WORKON_HOME
    source ~/.local/bin/virtualenvwrapper.sh

就是这样,根本不使用sudo任何功能,并且您的Python环境在中~/.local,与操作系统的Python完全分开。免责声明:不确定virtualenvwrapper这种情况下的兼容性-我无法在我的系统上测试它:-)

I think Glyph means do something like this:

  1. Create a directory ~/.local, if it doesn’t already exist.
  2. In your ~/.bashrc, ensure that ~/.local/bin is on PATH and that ~/.local is on PYTHONPATH.
  3. Create a file ~/.pydistutils.cfg which contains

    [install]
    prefix=~/.local
    

    It’s a standard ConfigParser-format file.

  4. Download distribute_setup.py and run python distribute_setup.py (no sudo). If it complains about a non-existing site-packages directory, create it manually:

    mkdir -p ~/.local/lib/python2.7/site-packages/

  5. Run which easy_install to verify that it’s coming from ~/.local/bin

  6. Run pip install virtualenv
  7. Run pip install virtualenvwrapper
  8. Create a virtual env containing folder, say ~/.virtualenvs
  9. In ~/.bashrc add

    export WORKON_HOME
    source ~/.local/bin/virtualenvwrapper.sh
    

That’s it, no use of sudo at all and your Python environment is in ~/.local, completely separate from the OS’s Python. Disclaimer: Not sure how compatible virtualenvwrapper is in this scenario – I couldn’t test it on my system :-)


回答 2

如果您按照我在此答案中链接的若干教程中的建议进行操作,则无需在Walker和Vinay的答案中进行一些复杂的“手动”步骤即可获得所需的效果。如果您使用的是Ubuntu:

sudo apt-get install python-pip python-dev

在OS X中,可以通过使用自制软件安装python来实现等效功能(此处有更多详细信息)。

brew install python

随着pip安装,你可以用它来获得剩余的包(可以省略sudo在OS X,如您使用的Python的安装)。

sudo pip install virtualenvwrapper

(这是您需要全局安装的唯一软件包,我怀疑它是否会与操作系统中的任何系统级冲突。如果您想超级安全,可以保留发行版的版本sudo apt-get install virtualenvwrapper

注意:在Ubuntu 14.04中,pip install会出现一些错误,因此我使用pip3 install virtualenv virtualenvwrapper并添加VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3到我的.bashrc/.zshrc文件中。

然后添加到.bashrc文件中

export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh

并获取它

. ~/.bashrc

基本上就是这样。现在唯一的决定是是否要创建一个virtualenv来包含系统级程序包

mkvirtualenv --system-site-packages foo

在不需要重新安装现有系统软件包的情况下,它们会与系统解释器的版本符号链接。注意:您仍然可以安装新软件包并升级现有的包含在系统中的软件包,而无需使用sudo-我对其进行了测试,并且它可以在不中断系统解释器的情况下正常运行。

kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0

如果您想要一个完全独立的环境,那么另一种方法是

mkvirtualenv --no-site-packages bar

或假设这是默认选项,只需

mkvirtualenv bar

结果是您拥有了一个新的virtualenv,您可以在其中自由而无须地安装自己喜欢的软件包

pip install flask

If you follow the steps advised in several tutorials I linked in this answer, you can get the desired effect without the somewhat complicated “manual” steps in Walker’s and Vinay’s answers. If you’re on Ubuntu:

sudo apt-get install python-pip python-dev

The equivalent is achieved in OS X by using homebrew to install python (more details here).

brew install python

With pip installed, you can use it to get the remaining packages (you can omit sudo in OS X, as you’re using your local python installation).

sudo pip install virtualenvwrapper

(these are the only packages you need installed globally and I doubt that it will clash with anything system-level from the OS. If you want to be super-safe, you can keep the distro’s versions sudo apt-get install virtualenvwrapper)

Note: in Ubuntu 14.04 I receive some errors with pip install, so I use pip3 install virtualenv virtualenvwrapper and add VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 to my .bashrc/.zshrc file.

You then append to your .bashrc file

export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh

and source it

. ~/.bashrc

This is basically it. Now the only decision is whether you want to create a virtualenv to include system-level packages

mkvirtualenv --system-site-packages foo

where your existing system packages don’t have to be reinstalled, they are symlinked to the system interpreter’s versions. Note: you can still install new packages and upgrade existing included-from-system packages without sudo – I tested it and it works without any disruptions of the system interpreter.

kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0

The alternative, if you want a completely separated environment, is

mkvirtualenv --no-site-packages bar

or given that this is the default option, simply

mkvirtualenv bar

The result is that you have a new virtualenv where you can freely and sudolessly install your favourite packages

pip install flask

回答 3

从Python 3.4开始

Python 3.3添加了venv模块,Python 3.4添加了surepip模块。这使自举点变得简单:

python -m确保

可能在venv虚拟环境中呼吁这样做之前。

PEP 453中描述了保证的点子。

Python 3.4 onward

Python 3.3 adds the venv module, and Python 3.4 adds the ensurepip module. This makes bootstrapping pip as easy as:

python -m ensurepip

Perhaps preceded by a call to venv to do so inside a virtual environment.

Guaranteed pip is described in PEP 453.


回答 4

在Ubuntu上:

sudo apt-get install python-virtualenv

该软件包python-pip是一个依赖项,因此也将被安装。

On Ubuntu:

sudo apt-get install python-virtualenv

The package python-pip is a dependency, so it will be installed as well.


回答 5

我做了这个程序供我们在工作中使用。

cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1

$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper

# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh

mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.

安全意识的要点:

  1. curl会进行ssl验证。wget没有。
  2. 从pip 1.3.1开始,pip还执行ssl验证。
  3. 与github tarball相比,更少的用户可以上传pypi tarball。

I made this procedure for us to use at work.

cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1

$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper

# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh

mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.

Key points for the security minded:

  1. curl does ssl validation. wget doesn’t.
  2. Starting from pip 1.3.1, pip also does ssl validation.
  3. Fewer users can upload the pypi tarball than a github tarball.

回答 6

更新:自2013年7月起,该项目不再维护。作者建议使用pyenv。(pyenv没有对virtualenv的内置支持,但是可以很好地使用它。)

Pythonbrew是python的版本管理器,并支持virtualenv。

使用venvs安装pythonbrew和python版本后,真的很容易:

# Initializes the virtualenv 
pythonbrew venv init

# Create a virtual/sandboxed environment 
pythonbrew venv create mycoolbundle  

# Use it 
pythonbrew venv use mycoolbundle

Update: As of July 2013 this project is no longer maintained. The author suggests using pyenv. (pyenv does not have built-in support for virtualenv, but plays nice with it.)

Pythonbrew is a version manager for python and comes with support for virtualenv.

After installing pythonbrew and a python-version using venvs is really easy:

# Initializes the virtualenv 
pythonbrew venv init

# Create a virtual/sandboxed environment 
pythonbrew venv create mycoolbundle  

# Use it 
pythonbrew venv use mycoolbundle

回答 7

如果您确定这是您要执行的操作,则执行sudo python setup.py安装没有问题。

不同之处在于它将使用操作系统的site-packages目录作为要复制的.py文件的目标。

因此,如果您希望点子在整个范围内都可访问,那可能就是方法。我并不是说其他​​人的方法是不好的,但这可能很公平。

There is no problem to do sudo python setup.py install, if you’re sure it’s what you want to do.

The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.

so, if you want pip to be accessible os wide, that’s probably the way to go. I do not say that others way are bad, but this is probably fair enough.


回答 8

安装ActivePython。它包括pip,virtualenv和Distribute。

Install ActivePython. It includes pip, virtualenv and Distribute.


回答 9

我最近遇到了同样的问题。我越来越偏爱“始终使用virtualenv”的心态,所以我的问题是使用pip安装virtualenv,而没有将distribution安装到我的全局目录或用户site-packages目录中。为此,我手动下载了distribute,pip和virtualenv,然后为每个文件运行“ python setup.py install –prefix〜/ .local / python-private”(临时设置为PYTHONPATH =〜/ .local / python-private),以便安装脚本能够找到分发)。我已经将virtualenv脚本移到了我在PATH上的另一个目录中,并对其进行了编辑,以便可以在sys.path上找到分发和virtualenv模块。Tada:我没有在/ usr,/ usr / local或用户站点软件包目录中安装任何东西,但是我可以在任何地方运行virtualenv,在该virtualenv中我得到了pip。

I came across the same problem recently. I’m becoming more partial to the “always use a virtualenv” mindset, so my problem was to install virtualenv with pip without installing distribute to my global or user site-packages directory. To do this, I manually downloaded distribute, pip and virtualenv, and for each one I ran “python setup.py install –prefix ~/.local/python-private” (with a temporary setting of PYTHONPATH=~/.local/python-private) so that setup scripts were able to find distribute). I’ve moved the virtualenv script to another directory I have on my PATH and edited it so that the distribute and virtualenv modules can be found on sys.path. Tada: I did not install anything to /usr, /usr/local or my user site-packages dir, but I can run virtualenv anywhere, and in that virtualenv I get pip.


回答 10

在较旧的操作系统提供的Python版本之上,即使在virtualenv中也安装了升级的SSL模块时,我遇到了各种各样的问题(请参阅下文),所以我现在使用pyenv

pyenv使安装新的Python版本变得非常容易,并支持virtualenvs。入门是比的食谱在其他的答案中所列的virtualenv容易:

  • 在Mac上,键入brew install pyenv,在Linux上,使用pyenv-installer
  • 这将为您提供内置的virtualenv支持以及Python版本切换(如果需要)
  • 与Python 2或3搭配使用时效果很好,可以一次安装多个版本

这样可以很好地将“新Python”版本和virtualenv与系统Python隔离开。因为您可以轻松地使用更新的Python(第2.7.9版),所以SSL模块已经升级,当然,像任何现代的virtualenv设置一样,您与系统Python模块隔离。

一些不错的教程:

pyenv-virtualenv插件现在内建-类型pyenv commands | grep virtualenv检查。我不会首先使用pyenv-virtualenvwrapper插件-了解如何与pyenv集成程度更高的pyenv-virtualenv进行交流,因为这涵盖了virtualenvwrapper的大部分工作。

pyenv建模rbenv(用于Ruby版本切换的好工具),并且其唯一依赖项是bash。

  • pyenv与非常相似的名称无关pyvenv-它是等效的virtualenv,是最新Python 3版本的一部分,并且不处理Python版本切换

注意事项

关于pyenv的两个警告:

  1. 它只能从bash或类似贝壳的作品-或者更具体地说,pyenv-的virtualenv插件不一样dash,这是/bin/sh在Ubuntu或Debian的。
  2. 它必须从交互式登录外壳程序(例如bash --login使用终端)运行,使用诸如Ansible之类的自动化工具并不总是很容易实现

因此,pyenv最适合交互式使用,而对脚本服务器则不太好。

SSL模块问题

使用的原因之一pyenv是,在使用较早的系统提供的Python版本时,升级Python SSL模块常常会遇到问题:

  • Ubuntu 14.04 包含Python 2.7.6,这需要大量的工作才能将其升级到正确的SSL模块,因此它可以将SNI(服务器名称指示)作为客户端进行处理。(我为此编写了一些Ansible脚本,这很痛苦,在某些情况下仍然会中断。)
  • 升级的SSL模块将变得更加重要,因为Python.org网站仅在2017年和2018年才迁移到TLS 1.2

I’ve had various problems (see below) installing upgraded SSL modules, even inside a virtualenv, on top of older OS-provided Python versions, so I now use pyenv.

pyenv makes it very easy to install new Python versions and supports virtualenvs. Getting started is much easier than the recipes for virtualenv listed in other answers:

  • On Mac, type brew install pyenv and on Linux, use pyenv-installer
  • this gets you built-in virtualenv support as well as Python version switching (if required)
  • works well with Python 2 or 3, can have many versions installed at once

This works very well to insulate the “new Python” version and virtualenv from system Python. Because you can easily use a more recent Python (post 2.7.9), the SSL modules are already upgraded, and of course like any modern virtualenv setup you are insulated from the system Python modules.

A couple of nice tutorials:

The pyenv-virtualenv plugin is now built in – type pyenv commands | grep virtualenv to check. I wouldn’t use the pyenv-virtualenvwrapper plugin to start with – see how you get on with pyenv-virtualenv which is more integrated into pyenv, as this covers most of what virtualenvwrapper does.

pyenv is modelled on rbenv (a good tool for Ruby version switching) and its only dependency is bash.

  • pyenv is unrelated to the very similarly named pyvenv – that is a virtualenv equivalent that’s part of recent Python 3 versions, and doesn’t handle Python version switching

Caveats

Two warnings about pyenv:

  1. It only works from a bash or similar shell – or more specifically, the pyenv-virtualenv plugin doesn’t like dash, which is /bin/sh on Ubuntu or Debian.
  2. It must be run from an interactive login shell (e.g. bash --login using a terminal), which is not always easy to achieve with automation tools such as Ansible.

Hence pyenv is best for interactive use, and less good for scripting servers.

SSL module problems

One reason to use pyenv is that there are often problems with upgrading Python SSL modules when using older system-provided Python versions:


回答 11

  • 您可以执行此操作而无需在python本身中安装任何东西。

  • 您不需要sudo或任何特权。

  • 您无需查找virtualenvtar文件的最新版本

  • 您无需在bash脚本中编辑版本信息即可保持最新状态。

  • 你不需要curl/ wgettar安装,也不pipeasy_install

  • 这适用于2.7和3.X

将以下内容保存到/tmp/initvenv.py

将来导入print_function

import os, sys, shutil, tempfile, subprocess, tarfile, hashlib

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
    # read the latest version from PyPI
    f = urlopen("https://pypi.python.org/pypi/virtualenv/")
    # retrieve the .tar.gz file
    tar_found = False
    url = None
    sha256 = None
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if tar_found:
            if 'sha256' in line:
                sha256 = line.split('data-clipboard-text')[1].split('"')[1]
                break
            continue
        if not tar_found and 'tar.gz">' not in line:
            continue
        tar_found = True
        for url in line.split('"'):
            if url.startswith('https'):
                break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    os.chdir(tmp_dir)
    data = urlopen(url).read()
    data_sha256 = hashlib.sha256(data).hexdigest()
    if sha256 != data_sha256:
        print('sha256 not correct')
        print(sha256)
        print(data_sha256)
        sys.exit(1)
    with open(file_name, 'wb') as fp:
        fp.write(data)
    tar = tarfile.open(file_name)
    tar.extractall()
    tar.close()
    os.chdir(file_name.replace('.tar.gz', ''))
    print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
                                  [sys.argv[1]]).decode('utf-8'), end='')
    if len(sys.argv) > 2:
        print(subprocess.check_output([
            os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +

            sys.argv[2:]).decode('utf-8'), end='')
except:
    raise
finally:
    shutil.rmtree(tmp_dir)  # always clean up

并用作

python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]

例如(如果您确实需要的distribute兼容性层setuptools

python /tmp/initvenv.py venv distribute

请注意,使用较旧的python版本,这可能会给您InsecurePlatformWarnings¹。

获得virtualenv(例如名称venv)后,您可以使用virtualenv刚刚安装的虚拟环境来设置另一个virtualenv :

venv/bin/virtualenv venv2

虚拟环境包装器

我建议在一次设置后也查看一下virtualenvwrapper

% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper

和激活(可以通过您的登录脚本完成):

% source venv/bin/virtualenvwrapper.sh

您可以执行以下操作:

% mktmpenv 
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)% 

¹ 我还没有找到抑制警告的方法。可以在pip和/或中解决它request,但开发人员相互指出是原因。我得到了通常不切实际的建议,将我使用的python版本升级到最新版本。我确信这会中断我的Linux Mint 17安装。幸运的是pip缓存了软件包,因此每次安装软件包时仅发出一次警告。

  • You can do this without installing anything into python itself.

  • You don’t need sudo or any privileges.

  • You don’t need to find the latest version of a virtualenv tar file

  • You don’t need to edit version info in a bash script to keep things up-to-date.

  • You don’t need curl/wget or tar installed, nor pip or easy_install

  • this works for 2.7 as well as for 3.X

Save the following to /tmp/initvenv.py:

from future import print_function

import os, sys, shutil, tempfile, subprocess, tarfile, hashlib

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
    # read the latest version from PyPI
    f = urlopen("https://pypi.python.org/pypi/virtualenv/")
    # retrieve the .tar.gz file
    tar_found = False
    url = None
    sha256 = None
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if tar_found:
            if 'sha256' in line:
                sha256 = line.split('data-clipboard-text')[1].split('"')[1]
                break
            continue
        if not tar_found and 'tar.gz">' not in line:
            continue
        tar_found = True
        for url in line.split('"'):
            if url.startswith('https'):
                break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    os.chdir(tmp_dir)
    data = urlopen(url).read()
    data_sha256 = hashlib.sha256(data).hexdigest()
    if sha256 != data_sha256:
        print('sha256 not correct')
        print(sha256)
        print(data_sha256)
        sys.exit(1)
    with open(file_name, 'wb') as fp:
        fp.write(data)
    tar = tarfile.open(file_name)
    tar.extractall()
    tar.close()
    os.chdir(file_name.replace('.tar.gz', ''))
    print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
                                  [sys.argv[1]]).decode('utf-8'), end='')
    if len(sys.argv) > 2:
        print(subprocess.check_output([
            os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +

            sys.argv[2:]).decode('utf-8'), end='')
except:
    raise
finally:
    shutil.rmtree(tmp_dir)  # always clean up

and use it as

python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]

e.g. (if you really need the distribute compatibility layer for setuptools)

python /tmp/initvenv.py venv distribute

Please note that, with older python versions, this might give you InsecurePlatformWarnings¹.

Once you have your virtualenv (name e.g. venv) you can setup another virtualenv by using the virtualenv just installed:

venv/bin/virtualenv venv2

virtualenvwrapper

I recommend taking a look at virtualenvwrapper as well, after a one time setup:

% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper

and activation (can be done from your login script):

% source venv/bin/virtualenvwrapper.sh

you can do things like:

% mktmpenv 
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)% 

¹ I have not found a way to suppress the warning. It could be solved in pip and/or request, but the developers point to each other as the cause. I got the, often non-realistic, recommendation to upgrade the python version I was using to the latest version. I am sure this would break e.g my Linux Mint 17 install. Fortunately pip caches packages, so the Warning is made only once per package install.


回答 12

在Virtualenv官方网站上有很好的说明。https://pypi.python.org/pypi/virtualenv

基本上我做什么,是安装pipsudo easy_install pip,然后用于sudo pip install virtualenv再创建一个环境:virtualenv my_env(命名为你想要的),下面是我所做的:virtualenv --distribute my_env; 其安装distributepip在我的virtualenv。

再次,按照virtualenv页面上的说明进行操作。

有点麻烦,来自Ruby; P

There are good instructions on the Virtualenv official site. https://pypi.python.org/pypi/virtualenv

Basically what I did, is install pip with sudo easy_install pip, then used sudo pip install virtualenv then created an environment with: virtualenv my_env (name it what you want), following that I did: virtualenv --distribute my_env; which installed distribute and pip in my virtualenv.

Again, follow the instruction on the virtualenv page.

Kind of a hassle, coming from Ruby ;P


回答 13

这是安装virtualenvwrapper(this的更新)的一种好方法。

下载virtualenv-1.11.4(可在此处找到最新信息),将其解压缩,打开terminal

# Create a bootstrapenv and activate it:
$ cd ~
$ python <path to unzipped folder>/virtualenv.py bootstrapenv
$ source bootstrapenv/bin/activate

# Install virtualenvwrapper:
$ pip install virtualenvwrapper
$ mkdir -p ~/bootstrapenv/Envs

# append it to file `.bashrc`
$ vi ~/.bashrc
  source ~/bootstrapenv/bin/activate
  export WORKON_HOME=~/bootstrapenv/Envs
  source ~/bootstrapenv/bin/virtualenvwrapper.sh

# run it now.
$ source ~/.bashrc

这就是它,现在你可以使用mkvirtualenv env1lsvirtualenv…等

注意:您可以删除virtualenv-1.11.4,并virtualenv-1.11.4.zip从下载文件夹。

Here is a nice way to install virtualenvwrapper(update of this).

Download virtualenv-1.11.4 (you can find latest at here), Unzip it, open terminal

# Create a bootstrapenv and activate it:
$ cd ~
$ python <path to unzipped folder>/virtualenv.py bootstrapenv
$ source bootstrapenv/bin/activate

# Install virtualenvwrapper:
$ pip install virtualenvwrapper
$ mkdir -p ~/bootstrapenv/Envs

# append it to file `.bashrc`
$ vi ~/.bashrc
  source ~/bootstrapenv/bin/activate
  export WORKON_HOME=~/bootstrapenv/Envs
  source ~/bootstrapenv/bin/virtualenvwrapper.sh

# run it now.
$ source ~/.bashrc

That is it, now you can use mkvirtualenv env1, lsvirtualenv ..etc

Note: you can delete virtualenv-1.11.4 and virtualenv-1.11.4.zip from Downloads folders.


回答 14

好消息是,如果您已安装python3.4,则已经安装了pyvenv。所以就

pyvenv project_dir
source project_dir/bin/activate
python --version   
python 3.4.*

现在,在此虚拟环境中,您可以使用pip为该项目安装模块。

离开这个虚拟环境,

deactivate

The good news is if you have installed python3.4, pyvenv is already been installed. So, Just

pyvenv project_dir
source project_dir/bin/activate
python --version   
python 3.4.*

Now in this virtual env, you can use pip to install modules for this project.

Leave this virtual env , just

deactivate

setuptools setup.py文件中install_requires kwarg的参考requirements.txt

问题:setuptools setup.py文件中install_requires kwarg的参考requirements.txt

我有一个requirements.txt与Travis-CI一起使用的文件。在requirements.txt和中都重复要求似乎很愚蠢setup.py,所以我希望将文件句柄传递给install_requiresin setuptools.setup

这可能吗?如果是这样,我应该怎么做呢?

这是我的requirements.txt文件:

guessit>=0.5.2
tvdb_api>=1.8.2
hachoir-metadata>=1.3.3
hachoir-core>=1.3.3
hachoir-parser>=1.3.4

I have a requirements.txt file that I’m using with Travis-CI. It seems silly to duplicate the requirements in both requirements.txt and setup.py, so I was hoping to pass a file handle to the install_requires kwarg in setuptools.setup.

Is this possible? If so, how should I go about doing it?

Here is my requirements.txt file:

guessit>=0.5.2
tvdb_api>=1.8.2
hachoir-metadata>=1.3.3
hachoir-core>=1.3.3
hachoir-parser>=1.3.4

回答 0

你可以翻转它周围,列表中的依赖关系setup.py,并有单字符-点.-在requirements.txt代替。


另外,即使不建议使用,也可以requirements.txt通过以下技巧(通过进行测试pip 9.0.1)来分析文件(如果它没有通过URL引用任何外部要求):

install_reqs = parse_requirements('requirements.txt', session='hack')

但是,这不会过滤环境标记


在pip的旧版本中(更具体地讲,版本早于6.0),可以使用公共API来实现此目的。需求文件可以包含注释(#),也可以包含其他一些文件(--requirement-r)。因此,如果您确实要解析a requirements.txt,则可以使用pip解析器:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

You can flip it around and list the dependencies in setup.py and have a single character — a dot . — in requirements.txt instead.


Alternatively, even if not advised, it is still possible to parse the requirements.txt file (if it doesn’t refer any external requirements by URL) with the following hack (tested with pip 9.0.1):

install_reqs = parse_requirements('requirements.txt', session='hack')

This doesn’t filter environment markers though.


In old versions of pip, more specifically older than 6.0, there is a public API that can be used to achieve this. A requirement file can contain comments (#) and can include some other files (--requirement or -r). Thus, if you really want to parse a requirements.txt you can use the pip parser:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

回答 1

在它面前,它似乎是requirements.txtsetup.py是愚蠢的重复,而是要明白,虽然形式是相似的,预定的功能有很大的不同是很重要的。

程序包作者在指定依赖项时的目的是说:“无论您在何处安装此程序包,都需要其他程序包,此程序包才能工作。”

相反,部署作者(可能在不同时间是同一个人)的工作不同,他们说:“这是我们收集并测试过的软件包列表,现在我需要安装”。

软件包作者针对各种各样的场景进行了写作,因为他们将自己的工作放到那里以他们可能不了解的方式使用,并且无法知道将在软件包旁边安装哪些软件包。为了成为一个好邻居并避免依赖版本与其他软件包冲突,他们需要指定尽可能广泛的依赖版本。这就是install_requiressetup.py做。

部署作者写的是一个非常不同,非常特定的目标:在特定计算机上安装的已安装应用程序或服务的单个实例。为了精确控制部署,并确保测试和部署了正确的软件包,部署作者必须指定要安装的每个软件包的确切版本和源位置,包括依赖关系和依赖关系。使用此规范,可以将部署重复地应用于多台计算机,或在测试计算机上进行测试,并且部署作者可以确信每次都部署了相同的程序包。这就是一个requirements.txt

因此,您可以看到,尽管它们看起来都像是一个很大的软件包和版本列表,但是这两件事的工作却截然不同。而且混合起来并弄错它肯定很容易!但是考虑这一点的正确方法是,requirements.txt对所有各种setup.py软件包文件中的需求提出的“问题”进行“解答” 。而不是手工编写,它通常是通过告诉pip查看setup.py一组所需软件包中的所有文件,找到它认为符合所有要求的一组软件包,然后在安装后冻结来生成的。 ”将软件包列表转换为文本文件(这就是pip freeze名称的来源)。

因此,外卖:

  • setup.py应该声明仍然可用的最宽松的依赖版本。它的工作是说特定的软件包可以使用什么。
  • requirements.txt是一个定义整个安装工作​​的部署清单,不应将其视为与任何一个软件包捆绑在一起。它的工作是为完成部署工作而声明所有必要软件包的详尽清单。
  • 由于这两件事具有如此不同的内容和存在的原因,因此简单地将其中一项复制到另一项中是不可行的。

参考文献:

On the face of it, it does seem that requirements.txt and setup.py are silly duplicates, but it’s important to understand that while the form is similar, the intended function is very different.

The goal of a package author, when specifying dependencies, is to say “wherever you install this package, these are the other packages you need, in order for this package to work.”

In contrast, the deployment author (which may be the same person at a different time) has a different job, in that they say “here’s the list of packages that we’ve gathered together and tested and that I now need to install”.

The package author writes for a wide variety of scenarios, because they’re putting their work out there to be used in ways they may not know about, and have no way of knowing what packages will be installed alongside their package. In order to be a good neighbor and avoid dependency version conflicts with other packages, they need to specify as wide a range of dependency versions as can possibly work. This is what install_requires in setup.py does.

The deployment author writes for a very different, very specific goal: a single instance of an installed application or service, installed on a particular computer. In order to precisely control a deployment, and be sure that the right packages are tested and deployed, the deployment author must specify the exact version and source-location of every package to be installed, including dependencies and dependency’s dependencies. With this spec, a deployment can be repeatably applied to several machines, or tested on a test machine, and the deployment author can be confident that the same packages are deployed every time. This is what a requirements.txt does.

So you can see that, while they both look like a big list of packages and versions, these two things have very different jobs. And it’s definitely easy to mix this up and get it wrong! But the right way to think about this is that requirements.txt is an “answer” to the “question” posed by the requirements in all the various setup.py package files. Rather than write it by hand, it’s often generated by telling pip to look at all the setup.py files in a set of desired packages, find a set of packages that it thinks fits all the requirements, and then, after they’re installed, “freeze” that list of packages into a text file (this is where the pip freeze name comes from).

So the takeaway:

  • setup.py should declare the loosest possible dependency versions that are still workable. Its job is to say what a particular package can work with.
  • requirements.txt is a deployment manifest that defines an entire installation job, and shouldn’t be thought of as tied to any one package. Its job is to declare an exhaustive list of all the necessary packages to make a deployment work.
  • Because these two things have such different content and reasons for existing, it’s not feasible to simply copy one into the other.

References:


回答 2

它不能使用文件句柄。该install_requires参数可以仅仅是一个字符串或字符串列表

当然,您可以在设置脚本中读取文件,并将其作为字符串列表传递给install_requires

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

It can’t take a file handle. The install_requires argument can only be a string or a list of strings.

You can, of course, read your file in the setup script and pass it as a list of strings to install_requires.

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

回答 3

需求文件使用扩展的pip格式,仅当您需要setup.py用更严格的约束来补充时(例如,指定某些依赖项必须来自的确切网址,或pip freeze将整个包冻结为已知工作的输出),该文件才有用版本。如果您不需要额外的约束,请仅使用setup.py。如果您觉得确实需要运送requirements.txt,可以将其放在一行中:

.

这将是有效的,并且完全引用setup.py同一目录中的内容。

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don’t need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.


回答 4

虽然不是该问题的确切答案,但我还是推荐Donald Stufft的博客文章,网址https://caremad.io/2013/07/setup-vs-requirement/,以很好地解决这个问题。我一直在使用它取得巨大的成功。

简而言之, requirements.txt这不是setup.py替代方案,而是部署的补充。在中保持适当的软件包依赖关系抽象setup.py。设置一个requirements.txt或多个’em以获取特定版本的软件包依赖项以进行开发,测试或生产。

例如,包含在回购下的软件包中 deps/

# fetch specific dependencies
--no-index
--find-links deps/

# install package
# NOTE: -e . for editable mode
.

pip执行包的程序setup.py并安装在中声明的依赖项的特定版本install_requires。没有重复性,并且保留了两个工件的目的。

While not an exact answer to the question, I recommend Donald Stufft’s blog post at https://caremad.io/2013/07/setup-vs-requirement/ for a good take on this problem. I’ve been using it to great success.

In short, requirements.txt is not a setup.py alternative, but a deployment complement. Keep an appropriate abstraction of package dependencies in setup.py. Set requirements.txt or more of ’em to fetch specific versions of package dependencies for development, testing, or production.

E.g. with packages included in the repo under deps/:

# fetch specific dependencies
--no-index
--find-links deps/

# install package
# NOTE: -e . for editable mode
.

pip executes package’s setup.py and installs the specific versions of dependencies declared in install_requires. There’s no duplicity and the purpose of both artifacts is preserved.


回答 5

使用parse_requirements存在问题,因为未公开记录和支持pip API。在第1.6点中,该功能实际上正在移动,因此该功能的现有用途可能会中断。

消除setup.py和之间重复的一种更可靠的方法requirements.txt是特定于您的依赖项setup.py,然后将其-e .放入requirements.txt文件中。从一个有些信息pip为什么这是去一个更好的办法开发人员可以在这里找到:https://caremad.io/blog/setup-vs-requirement/

Using parse_requirements is problematic because the pip API isn’t publicly documented and supported. In pip 1.6, that function is actually moving, so existing uses of it are likely to break.

A more reliable way to eliminate duplication between setup.py and requirements.txt is to specific your dependencies in setup.py and then put -e . into your requirements.txt file. Some information from one of the pip developers about why that’s a better way to go is available here: https://caremad.io/blog/setup-vs-requirement/


回答 6

以上大多数其他答案不适用于当前版本的pip API。这是使用当前版本的pip(在撰写本文时为6.0.8,在7.1.2中也可以使用。)的正确方法。您可以使用pip -V检查版本。

from pip.req import parse_requirements
from pip.download import PipSession

install_reqs = parse_requirements(<requirements_path>, session=PipSession())

reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
    ....
)

*正确,因为这是对当前点使用parse_requirements的方式。仍然可能不是最好的方法,因为正如上面的海报所述,pip并没有真正维护API。

Most of the other answers above don’t work with the current version of pip’s API. Here is the correct* way to do it with the current version of pip (6.0.8 at the time of writing, also worked in 7.1.2. You can check your version with pip -V).

from pip.req import parse_requirements
from pip.download import PipSession

install_reqs = parse_requirements(<requirements_path>, session=PipSession())

reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
    ....
)

* Correct, in that it is the way to use parse_requirements with the current pip. It still probably isn’t the best way to do it, since, as posters above said, pip doesn’t really maintain an API.


回答 7

在Travis中安装当前软件包。这样可以避免使用requirements.txt文件。例如:

language: python
python:
  - "2.7"
  - "2.6"
install:
  - pip install -q -e .
script:
  - python runtests.py

Install the current package in Travis. This avoids the use of a requirements.txt file. For example:

language: python
python:
  - "2.7"
  - "2.6"
install:
  - pip install -q -e .
script:
  - python runtests.py

回答 8

from pip.req import parse_requirements 不适用于我,我认为它适用于我的requirements.txt中的空白行,但是此功能确实有效

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

from pip.req import parse_requirements did not work for me and I think it’s for the blank lines in my requirements.txt, but this function does work

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

回答 9

如果您不想强迫用户安装pip,可以使用以下方法模拟其行为:

import sys

from os import path as p

try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup, find_packages


def read(filename, parent=None):
    parent = (parent or __file__)

    try:
        with open(p.join(p.dirname(parent), filename)) as f:
            return f.read()
    except IOError:
        return ''


def parse_requirements(filename, parent=None):
    parent = (parent or __file__)
    filepath = p.join(p.dirname(parent), filename)
    content = read(filename, parent)

    for line_number, line in enumerate(content.splitlines(), 1):
        candidate = line.strip()

        if candidate.startswith('-r'):
            for item in parse_requirements(candidate[2:].strip(), filepath):
                yield item
        else:
            yield candidate

setup(
...
    install_requires=list(parse_requirements('requirements.txt'))
)

If you don’t want to force your users to install pip, you can emulate its behavior with this:

import sys

from os import path as p

try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup, find_packages


def read(filename, parent=None):
    parent = (parent or __file__)

    try:
        with open(p.join(p.dirname(parent), filename)) as f:
            return f.read()
    except IOError:
        return ''


def parse_requirements(filename, parent=None):
    parent = (parent or __file__)
    filepath = p.join(p.dirname(parent), filename)
    content = read(filename, parent)

    for line_number, line in enumerate(content.splitlines(), 1):
        candidate = line.strip()

        if candidate.startswith('-r'):
            for item in parse_requirements(candidate[2:].strip(), filepath):
                yield item
        else:
            yield candidate

setup(
...
    install_requires=list(parse_requirements('requirements.txt'))
)

回答 10

以下界面在点10中已弃用:

from pip.req import parse_requirements
from pip.download import PipSession

所以我将其切换为简单的文本解析:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

The following interface became deprecated in pip 10:

from pip.req import parse_requirements
from pip.download import PipSession

So I switched it just to simple text parsing:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

回答 11

这种简单的方法从中读取需求文件setup.py。这是Dmitiry S.答案的变形。此答案仅与Python 3.6+兼容。

DSrequirements.txt可以记录与特定的版本号具体要求,而setup.py可以记录与宽松版范围抽象的要求。

以下是我的摘录setup.py

import distutils.text_file
from pathlib import Path
from typing import List

def _parse_requirements(filename: str) -> List[str]:
    """Return requirements from requirements file."""
    # Ref: https://stackoverflow.com/a/42033122/
    return distutils.text_file.TextFile(filename=str(Path(__file__).with_name(filename))).readlines()

setup(...
      install_requires=_parse_requirements('requirements.txt'),
   ...)

请注意,这distutils.text_file.TextFile将删除注释。而且,根据我的经验,您显然不需要采取任何特殊步骤将需求文件捆绑在一起。

This simple approach reads the requirements file from setup.py. It is a variation of the answer by Dmitiry S.. This answer is compatible only with Python 3.6+.

Per D.S., requirements.txt can document concrete requirements with specific version numbers, whereas setup.py can document abstract requirements with loose version ranges.

Below is an excerpt of my setup.py.

import distutils.text_file
from pathlib import Path
from typing import List

def _parse_requirements(filename: str) -> List[str]:
    """Return requirements from requirements file."""
    # Ref: https://stackoverflow.com/a/42033122/
    return distutils.text_file.TextFile(filename=str(Path(__file__).with_name(filename))).readlines()

setup(...
      install_requires=_parse_requirements('requirements.txt'),
   ...)

Note that distutils.text_file.TextFile will strip comments. Also, per my experience, you apparently do not need to take any special step to bundle in the requirements file.


回答 12

小心parse_requirements行为!

请注意,pip.req.parse_requirements下划线将变为短划线。在发现它之前,这让我很生气。示例说明:

from pip.req import parse_requirements  # tested with v.1.4.1

reqs = '''
example_with_underscores
example-with-dashes
'''

with open('requirements.txt', 'w') as f:
    f.write(reqs)

req_deps = parse_requirements('requirements.txt')
result = [str(ir.req) for ir in req_deps if ir.req is not None]
print result

产生

['example-with-underscores', 'example-with-dashes']

BEWARE OF parse_requirements BEHAVIOUR!

Please note that pip.req.parse_requirements will change underscores to dashes. This was enraging me for a few days before I discovered it. Example demonstrating:

from pip.req import parse_requirements  # tested with v.1.4.1

reqs = '''
example_with_underscores
example-with-dashes
'''

with open('requirements.txt', 'w') as f:
    f.write(reqs)

req_deps = parse_requirements('requirements.txt')
result = [str(ir.req) for ir in req_deps if ir.req is not None]
print result

produces

['example-with-underscores', 'example-with-dashes']

回答 13

我为此创建了一个可重用的函数。它实际上解析需求文件的整个目录,并将它们设置为extras_require。

最新的始终可用在这里:https : //gist.github.com/akatrevorjay/293c26fefa24a7b812f5

import glob
import itertools
import os

# This is getting ridiculous
try:
    from pip._internal.req import parse_requirements
    from pip._internal.network.session import PipSession
except ImportError:
    try:
        from pip._internal.req import parse_requirements
        from pip._internal.download import PipSession
    except ImportError:
        from pip.req import parse_requirements
        from pip.download import PipSession


def setup_requirements(
        patterns=[
            'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
        ],
        combine=True):
    """
    Parse a glob of requirements and return a dictionary of setup() options.
    Create a dictionary that holds your options to setup() and update it using this.
    Pass that as kwargs into setup(), viola

    Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
    basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.

    Keep in mind all literally contains `all` packages in your extras.
    This means if you have conflicting packages across your extras, then you're going to have a bad time.
    (don't use all in these cases.)

    If you're running this for a Docker build, set `combine=True`.
    This will set `install_requires` to all distinct reqs combined.

    Example:

    >>> import setuptools
    >>> _conf = dict(
    ...     name='mainline',
    ...     version='0.0.1',
    ...     description='Mainline',
    ...     author='Trevor Joynson <github@trevor.joynson,io>',
    ...     url='https://trevor.joynson.io',
    ...     namespace_packages=['mainline'],
    ...     packages=setuptools.find_packages(),
    ...     zip_safe=False,
    ...     include_package_data=True,
    ... )
    >>> _conf.update(setup_requirements())
    >>> # setuptools.setup(**_conf)

    :param str pattern: Glob pattern to find requirements files
    :param bool combine: Set True to set install_requires to extras_require['all']
    :return dict: Dictionary of parsed setup() options
    """
    session = PipSession()

    # Handle setuptools insanity
    key_map = {
        'requirements': 'install_requires',
        'install': 'install_requires',
        'tests': 'tests_require',
        'setup': 'setup_requires',
    }
    ret = {v: set() for v in key_map.values()}
    extras = ret['extras_require'] = {}
    all_reqs = set()

    files = [glob.glob(pat) for pat in patterns]
    files = itertools.chain(*files)

    for full_fn in files:
        # Parse
        reqs = {
            str(r.req)
            for r in parse_requirements(full_fn, session=session)
            # Must match env marker, eg:
            #   yarl ; python_version >= '3.0'
            if r.match_markers()
        }
        all_reqs.update(reqs)

        # Add in the right section
        fn = os.path.basename(full_fn)
        barefn, _ = os.path.splitext(fn)
        key = key_map.get(barefn)

        if key:
            ret[key].update(reqs)
            extras[key] = reqs

        extras[barefn] = reqs

    if 'all' not in extras:
        extras['all'] = list(all_reqs)

    if combine:
        extras['install'] = ret['install_requires']
        ret['install_requires'] = list(all_reqs)

    def _listify(dikt):
        ret = {}

        for k, v in dikt.items():
            if isinstance(v, set):
                v = list(v)
            elif isinstance(v, dict):
                v = _listify(v)
            ret[k] = v

        return ret

    ret = _listify(ret)

    return ret


__all__ = ['setup_requirements']

if __name__ == '__main__':
    reqs = setup_requirements()
    print(reqs)

I created a reusable function for this. It actually parses an entire directory of requirements files and sets them to extras_require.

Latest always available here: https://gist.github.com/akatrevorjay/293c26fefa24a7b812f5

import glob
import itertools
import os

# This is getting ridiculous
try:
    from pip._internal.req import parse_requirements
    from pip._internal.network.session import PipSession
except ImportError:
    try:
        from pip._internal.req import parse_requirements
        from pip._internal.download import PipSession
    except ImportError:
        from pip.req import parse_requirements
        from pip.download import PipSession


def setup_requirements(
        patterns=[
            'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
        ],
        combine=True):
    """
    Parse a glob of requirements and return a dictionary of setup() options.
    Create a dictionary that holds your options to setup() and update it using this.
    Pass that as kwargs into setup(), viola

    Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
    basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.

    Keep in mind all literally contains `all` packages in your extras.
    This means if you have conflicting packages across your extras, then you're going to have a bad time.
    (don't use all in these cases.)

    If you're running this for a Docker build, set `combine=True`.
    This will set `install_requires` to all distinct reqs combined.

    Example:

    >>> import setuptools
    >>> _conf = dict(
    ...     name='mainline',
    ...     version='0.0.1',
    ...     description='Mainline',
    ...     author='Trevor Joynson <github@trevor.joynson,io>',
    ...     url='https://trevor.joynson.io',
    ...     namespace_packages=['mainline'],
    ...     packages=setuptools.find_packages(),
    ...     zip_safe=False,
    ...     include_package_data=True,
    ... )
    >>> _conf.update(setup_requirements())
    >>> # setuptools.setup(**_conf)

    :param str pattern: Glob pattern to find requirements files
    :param bool combine: Set True to set install_requires to extras_require['all']
    :return dict: Dictionary of parsed setup() options
    """
    session = PipSession()

    # Handle setuptools insanity
    key_map = {
        'requirements': 'install_requires',
        'install': 'install_requires',
        'tests': 'tests_require',
        'setup': 'setup_requires',
    }
    ret = {v: set() for v in key_map.values()}
    extras = ret['extras_require'] = {}
    all_reqs = set()

    files = [glob.glob(pat) for pat in patterns]
    files = itertools.chain(*files)

    for full_fn in files:
        # Parse
        reqs = {
            str(r.req)
            for r in parse_requirements(full_fn, session=session)
            # Must match env marker, eg:
            #   yarl ; python_version >= '3.0'
            if r.match_markers()
        }
        all_reqs.update(reqs)

        # Add in the right section
        fn = os.path.basename(full_fn)
        barefn, _ = os.path.splitext(fn)
        key = key_map.get(barefn)

        if key:
            ret[key].update(reqs)
            extras[key] = reqs

        extras[barefn] = reqs

    if 'all' not in extras:
        extras['all'] = list(all_reqs)

    if combine:
        extras['install'] = ret['install_requires']
        ret['install_requires'] = list(all_reqs)

    def _listify(dikt):
        ret = {}

        for k, v in dikt.items():
            if isinstance(v, set):
                v = list(v)
            elif isinstance(v, dict):
                v = _listify(v)
            ret[k] = v

        return ret

    ret = _listify(ret)

    return ret


__all__ = ['setup_requirements']

if __name__ == '__main__':
    reqs = setup_requirements()
    print(reqs)

回答 14

另一种可能的解决方案…

def gather_requirements(top_path=None):
    """Captures requirements from repo.

    Expected file format is: requirements[-_]<optional-extras>.txt

    For example:

        pip install -e .[foo]

    Would require:

        requirements-foo.txt

        or

        requirements_foo.txt

    """
    from pip.download import PipSession
    from pip.req import parse_requirements
    import re

    session = PipSession()
    top_path = top_path or os.path.realpath(os.getcwd())
    extras = {}
    for filepath in tree(top_path):
        filename = os.path.basename(filepath)
        basename, ext = os.path.splitext(filename)
        if ext == '.txt' and basename.startswith('requirements'):
            if filename == 'requirements.txt':
                extra_name = 'requirements'
            else:
                _, extra_name = re.split(r'[-_]', basename, 1)
            if extra_name:
                reqs = [str(ir.req) for ir in parse_requirements(filepath, session=session)]
                extras.setdefault(extra_name, []).extend(reqs)
    all_reqs = set()
    for key, values in extras.items():
        all_reqs.update(values)
    extras['all'] = list(all_reqs)
    return extras

然后使用…

reqs = gather_requirements()
install_reqs = reqs.pop('requirements', [])
test_reqs = reqs.pop('test', [])
...
setup(
    ...
    'install_requires': install_reqs,
    'test_requires': test_reqs,
    'extras_require': reqs,
    ...
)

Another possible solution…

def gather_requirements(top_path=None):
    """Captures requirements from repo.

    Expected file format is: requirements[-_]<optional-extras>.txt

    For example:

        pip install -e .[foo]

    Would require:

        requirements-foo.txt

        or

        requirements_foo.txt

    """
    from pip.download import PipSession
    from pip.req import parse_requirements
    import re

    session = PipSession()
    top_path = top_path or os.path.realpath(os.getcwd())
    extras = {}
    for filepath in tree(top_path):
        filename = os.path.basename(filepath)
        basename, ext = os.path.splitext(filename)
        if ext == '.txt' and basename.startswith('requirements'):
            if filename == 'requirements.txt':
                extra_name = 'requirements'
            else:
                _, extra_name = re.split(r'[-_]', basename, 1)
            if extra_name:
                reqs = [str(ir.req) for ir in parse_requirements(filepath, session=session)]
                extras.setdefault(extra_name, []).extend(reqs)
    all_reqs = set()
    for key, values in extras.items():
        all_reqs.update(values)
    extras['all'] = list(all_reqs)
    return extras

and then to use…

reqs = gather_requirements()
install_reqs = reqs.pop('requirements', [])
test_reqs = reqs.pop('test', [])
...
setup(
    ...
    'install_requires': install_reqs,
    'test_requires': test_reqs,
    'extras_require': reqs,
    ...
)

回答 15

我不建议这样做。正如多次提到的install_requiresrequirements.txt绝对不应该是同一列表。但是,由于涉及pip的专用内部API的周围存在许多误导性答案,因此可能值得寻找更明智的选择…

不需要piprequirements.txtsetuptools setup.py脚本中解析文件。该setuptools的项目已经包含在了所有必要的工具顶层pkg_resources

它或多或少看起来像这样:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

I would not recommend doing such a thing. As mentioned multiple times install_requires and requirements.txt are definitely not supposed to be the same list. But since there are a lot of misleading answers all around involving private internal APIs of pip, it might be worth looking at saner alternatives…

There is no need for pip to parse a requirements.txt file from a setuptools setup.py script. The setuptools project already contains all the necessary tools in its top level package pkg_resources.

It could more or less look like this:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

Notes:


回答 16

这个SO问题交叉发布我的答案,以获得另一个简单的pip版本证明解决方案。

try:  # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())

if __name__ == '__main__':
    setup(
        ...
        install_requires=[str(requirement.req) for requirement in requirements],
        ...
    )

然后,将所有需求requirements.txt放在项目根目录下即可。

Cross posting my answer from this SO question for another simple, pip version proof solution.

try:  # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())

if __name__ == '__main__':
    setup(
        ...
        install_requires=[str(requirement.req) for requirement in requirements],
        ...
    )

Then just throw in all your requirements under requirements.txt under project root directory.


回答 17

我这样做:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

I did this:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

回答 18

另一个parse_requirements将环境标记解析为extras_require以下内容的黑客:

from collections import defaultdict
from pip.req import parse_requirements

requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
    if r.markers:
        extras[':' + str(r.markers)].append(str(r.req))
    else:
        requirements.append(str(r.req))

setup(
    ...,
    install_requires=requirements,
    extras_require=extras
)

它应该同时支持sdist和二进制dists。

正如其他人所述,它parse_requirements有几个缺点,因此这不是您应该在公共项目上执行的操作,但对于内部/个人项目来说就足够了。

Yet another parse_requirements hack that also parses environment markers into extras_require:

from collections import defaultdict
from pip.req import parse_requirements

requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
    if r.markers:
        extras[':' + str(r.markers)].append(str(r.req))
    else:
        requirements.append(str(r.req))

setup(
    ...,
    install_requires=requirements,
    extras_require=extras
)

It should support both sdist and binary dists.

As stated by others, parse_requirements has several shortcomings, so this is not what you should do on public projects, but it may suffice for internal/personal projects.


回答 19

这是pip 9.0.1根据Romain的答案(requirements.txt根据当前环境标记进行解析和过滤)的完整技巧(已通过测试):

from pip.req import parse_requirements

requirements = []
for r in parse_requirements('requirements.txt', session='hack'):
    # check markers, such as
    #
    #     rope_py3k    ; python_version >= '3.0'
    #
    if r.match_markers():
        requirements.append(str(r.req))

print(requirements)

Here is a complete hack (tested with pip 9.0.1) based on Romain’s answer that parses requirements.txt and filters it according to current environment markers:

from pip.req import parse_requirements

requirements = []
for r in parse_requirements('requirements.txt', session='hack'):
    # check markers, such as
    #
    #     rope_py3k    ; python_version >= '3.0'
    #
    if r.match_markers():
        requirements.append(str(r.req))

print(requirements)

Python setup.py开发与安装

问题:Python setup.py开发与安装

在setup.py两个选项develop,并install混淆了我。根据此站点,使用develop创建到site-packages目录的特殊链接。

人们建议我使用python setup.py install全新安装,并且python setup.py develop对安装文件进行任何更改之后。

谁能阐明这些命令的用法?

Two options in setup.py develop and install are confusing me. According to this site, using develop creates a special link to site-packages directory.

People have suggested that I use python setup.py install for a fresh installation and python setup.py develop after any changes have been made to the setup file.

Can anyone shed some light on the usage of these commands?


回答 0

python setup.py install 用于安装(通常是第三方)您不会自行开发/修改/调试的软件包。

对于您自己的东西,您想要首先安装您的软件包,然后能够频繁编辑代码不必每次都重新安装该软件包-正是python setup.py develop这样:安装软件包(通常只是一个源文件夹)以某种方式可以让您在将代码安装到(虚拟)环境后方便地编辑代码,并使更改立即生效。

请注意,强烈建议使用pip install .(安装)和pip install -e .(开发人员安装)来安装软件包,因为setup.py直接调用将对许多依赖项(例如pull prereleases和不兼容的软件包版本)做错事,或者使软件包难以使用卸载pip

python setup.py install is used to install (typically third party) packages that you’re not going to develop/modify/debug yourself.

For your own stuff, you want to first install your package and then be able to frequently edit the code without having to re-install the package every time — and that is exactly what python setup.py develop does: it installs the package (typically just a source folder) in a way that allows you to conveniently edit your code after it’s installed to the (virtual) environment, and have the changes take effect immediately.

Note that it is highly recommended to use pip install . (install) and pip install -e . (developer install) to install packages, as invoking setup.py directly will do the wrong things for many dependencies, such as pull prereleases and incompatible package versions, or make the package hard to uninstall with pip.


回答 1

文档中。该develop不会安装软件包,但它会创建一个.egg-link部署目录回项目源代码目录。

因此,这就像安装,而不是复制到其中,site-packages而是添加了一个符号链接(.egg-link充当多平台符号链接)。

这样,您可以编辑源代码并直接查看更改,无需在每次进行少量更改时都重新安装。如果您是该项目的开发者,因此很有用,名称为develop。如果您只是在安装别人的软件包,则应使用install

From the documentation. The develop will not install the package but it will create a .egg-link in the deployment directory back to the project source code directory.

So it’s like installing but instead of copying to the site-packages it adds a symbolic link (the .egg-link acts as a multiplatform symbolic link).

That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop. If you are just installing someone else’s package you should use install


回答 2

人们在使用该develop方法时可能会发现有用的另一件事是可以--user选择不使用sudo进行安装。例如:

python setup.py develop --user

代替

sudo python setup.py develop

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

发行版,distutils,setuptools和distutils2之间的区别?

问题:发行版,distutils,setuptools和distutils2之间的区别?

情况

我正在尝试将开放源代码库移植到Python3。(SymPy,如果有人想知道的话。)

因此,2to3在为Python 3构建时,我需要自动运行。为此,我需要使用distribute。因此,我需要移植当前的系统(根据doctest)是distutils


问题

不幸的是,我不知道什么是这些模块-之间的区别distutilsdistributesetuptools。该文档最好是粗略的,因为它们似乎都是彼此的分支,旨在在大多数情况下兼容(但实际上并非全部)……等等。


问题

有人可以解释差异吗?我应该用什么?什么是最现代的解决方案?(Distribute顺便说一句,我也很感谢有关向移植的一些指南,但这超出了问题的范围……)

The Situation

I’m trying to port an open-source library to Python 3. (SymPy, if anyone is wondering.)

So, I need to run 2to3 automatically when building for Python 3. To do that, I need to use distribute. Therefore, I need to port the current system, which (according to the doctest) is distutils.


The Problem

Unfortunately, I’m not sure what’s the difference between these modules—distutils, distribute, setuptools. The documentation is sketchy as best, as they all seem to be a fork of one another, intended to be compatible in most circumstances (but actually, not all)…and so on, and so forth.


The Question

Could someone explain the differences? What am I supposed to use? What is the most modern solution? (As an aside, I’d also appreciate some guide on porting to Distribute, but that’s a tad beyond the scope of the question…)


回答 0

截至2020年3月,该问题的大多数其他答案已经过时了几年。当您遇到有关Python包装问题的建议时,请记住查看发布日期,并且不要相信过时的信息。

Python包装用户指南》值得一读。每个页面上都显示有“最后更新”日期,因此您可以检查手册的最新性,并且内容非常全面。它托管在Python Software Foundation的python.org的子域中,这本身就增加了可信度。“ 项目摘要”页面在这里尤其重要。

工具摘要:

以下是Python封装环境的摘要:

支持的工具:

弃用/废弃的工具:

  • distribute是的叉子setuptools。它共享相同的命名空间,因此,如果您安装了Distribute,则import setuptools实际上将导入使用Distribute分发的软件包。Distribute被合并回Setuptools 0.7中,因此您不再需要使用Distribute。实际上,Pypi上的版本只是安装Setuptools的兼容层。

  • distutils2就是把最好的尝试distutilssetuptoolsdistribute成为列入Python的标准库中的标准工具。想法是distutils2将其分发给旧的Python版本,distutils2并将其重命名packaging为Python 3.3,并将其包含在其标准库中。这些计划没有按计划进行,但是目前distutils2是一个废弃的项目。最新版本于2012年3月发布,其Pypi主页最终已更新以反映其死亡。

其他:

如果您有兴趣,还有其他工具,请阅读《 Python打包用户指南》中的“ 项目摘要 ”。我就不一一列举,不重复该网页,并随时回答匹配的问题,这是只有约distributedistutilssetuptoolsdistutils2

建议:

如果这一切对您来说都是新手,并且您不知道从哪里开始,那么我建议您将学习setuptools,和pipvirtualenv一起很好地结合使用。

如果你正在寻找到virtualenv,你可能有兴趣在这样一个问题:是什么区别venvpyvenvpyenvvirtualenvvirtualenvwrapper,等?。(是的,我知道,我和你一起吟。)

As of March 2020, most of the other answers to this question are several years out-of-date. When you come across advice on Python packaging issues, remember to look at the date of publication, and don’t trust out-of-date information.

The Python Packaging User Guide is worth a read. Every page has a “last updated” date displayed, so you can check the recency of the manual, and it’s quite comprehensive. The fact that it’s hosted on a subdomain of python.org of the Python Software Foundation just adds credence to it. The Project Summaries page is especially relevant here.

Summary of tools:

Here’s a summary of the Python packaging landscape:

Supported tools:

Deprecated/abandoned tools:

  • distribute was a fork of setuptools. It shared the same namespace, so if you had Distribute installed, import setuptools would actually import the package distributed with Distribute. Distribute was merged back into Setuptools 0.7, so you don’t need to use Distribute any more. In fact, the version on Pypi is just a compatibility layer that installs Setuptools.

  • distutils2 was an attempt to take the best of distutils, setuptools and distribute and become the standard tool included in Python’s standard library. The idea was that distutils2 would be distributed for old Python versions, and that distutils2 would be renamed to packaging for Python 3.3, which would include it in its standard library. These plans did not go as intended, however, and currently, distutils2 is an abandoned project. The latest release was in March 2012, and its Pypi home page has finally been updated to reflect its death.

Others:

There are other tools, if you are interested, read Project Summaries in the Python Packaging User Guide. I won’t list them all, to not repeat that page, and to keep the answer matching the question, which was only about distribute, distutils, setuptools and distutils2.

Recommendation:

If all of this is new to you, and you don’t know where to start, I would recommend learning setuptools, along with pip and virtualenv, which all work very well together.

If you’re looking into virtualenv, you might be interested in this question: What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, etc?. (Yes, I know, I groan with you.)


回答 1

我是distutils维护者和distutils2 / packaging贡献者。我在ConFoo 2011上谈论了Python封装,如今,我正在编写它的扩展版本。它尚未发布,因此以下是一些有助于定义内容的摘录。

  • Distutils是用于包装的标准工具。它可以满足简单的需求,但功能有限,扩展范围也不小。

  • Setuptools是一个旨在填补缺少的distutils功能并探索新方向的项目。在某些子社区中,这是事实上的标准。它使用了Python核心开发人员不喜欢的Monkey补丁和魔术。

  • Distribute是Setuptools的一个分支,由开发人员启动,觉得它的开发速度太慢并且无法对其进行开发。当distutils2由同一组启动时,其开发速度大大减慢。2013年8月更新:分发重新合并到setuptools中并停止使用。

  • Distutils2是一个新的distutils库,它是distutils代码库的一个分支,从安装工具(其中一些已在PEP中进行了详细讨论)中汲取了好主意,并且是受pip启发的基本安装程序。 用来导入Distutils2的实际名称packaging在Python 3.3+标准库中,或者distutils2在2.4+和3.1-3.2中。(将很快提供一个反向端口。) Distutils2并未发布Python 3.3版本,因此被搁置了。

更多信息:

我希望很快完成我的指南,它将包含有关每个图书馆的优缺点的更多信息以及过渡指南。

I’m a distutils maintainer and distutils2/packaging contributor. I did a talk about Python packaging at ConFoo 2011 and these days I’m writing an extended version of it. It’s not published yet, so here are excerpts that should help define things.

  • Distutils is the standard tool used for packaging. It works rather well for simple needs, but is limited and not trivial to extend.

  • Setuptools is a project born from the desire to fill missing distutils functionality and explore new directions. In some subcommunities, it’s a de facto standard. It uses monkey-patching and magic that is frowned upon by Python core developers.

  • Distribute is a fork of Setuptools that was started by developers feeling that its development pace was too slow and that it was not possible to evolve it. Its development was considerably slowed when distutils2 was started by the same group. 2013-August update: distribute is merged back into setuptools and discontinued.

  • Distutils2 is a new distutils library, started as a fork of the distutils codebase, with good ideas taken from setup tools (of which some were thoroughly discussed in PEPs), and a basic installer inspired by pip. The actual name you use to import Distutils2 is packaging in the Python 3.3+ standard library, or distutils2 in 2.4+ and 3.1–3.2. (A backport will be available soon.) Distutils2 did not make the Python 3.3 release, and it was put on hold.

More info:

I hope to finish my guide soon, it will contain more info about each library’s strong and weak points and a transition guide.


回答 2

注意:已弃用答案,现在分发已过时。自Python打包机构成立以来,该答案不再有效,并且已经做了很多工作来清理此问题。


是的,您知道了。:-o我认为目前首选的软件包是Distribute,它是setuptools的一个分支,是distutils(原始打包系统)的扩展。Setuptools并未得到维护,因此已被分叉并重命名,但是在安装时,它使用setuptools的软件包名称!我认为大多数Python开发人员现在都使用Distribute,并且可以肯定地说我确实这样做。

NOTE: Answer deprecated, Distribute now obsolete. This answer is no longer valid since the Python Packaging Authority was formed and has done a lot of work cleaning this up.


Yep, you got it. :-o I think at this time the preferred package is Distribute, which is a fork of setuptools, which are an extension of distutils (the original packaging system). Setuptools was not being maintained so is was forked and renamed, however when installed it uses the package name of setuptools! I think most Python developers now use Distribute, and I can say for sure that I do.


回答 3

我意识到我已经回答了您的第二个问题,但没有解决您原始问题中的毫无疑问的假设:

我正在尝试将开放源代码库(SymPy,如果有人想知道)移植到Python3。为此,在构建Python 3时,我需要自动运行2to3。

可能不是需要。其他策略请参见http://docs.python.org/dev/howto/pyporting

为此,我需要使用分配,

可能 :) distutils以不同的分发方式支持代码(不是docstrings)的构建时2to3转换:http : //docs.python.org/dev/howto/pyporting#during-installation

I realize that I have replied to your secondary question without addressing unquestioned assumptions in your original problem:

I’m trying to port an open-source library (SymPy, if anyone is wondering) to Python 3. To do this, I need to run 2to3 automatically when building for Python 3.

You may, not need. Other strategies are described at http://docs.python.org/dev/howto/pyporting

To do that, I need to use distribute,

You may :) distutils supports build-time 2to3 conversion for code (not docstrings), in a different manner that distribute’s: http://docs.python.org/dev/howto/pyporting#during-installation


回答 4

2014年底更新了这个问题,幸运的是,Continuum的“ conda ”软件包管理器已大大消除了Python的包装混乱。

特别是,conda可以快速创建conda“ 环境 ”。您可以使用不同版本的Python配置您的环境。例如:

conda create -n py34 python=3.4 anaconda

conda create -n py26 python=2.6 anaconda

将使用不同版本的Python创建两个(“ py34”或“ py26”)Python环境。

之后,您可以使用以下特定版本的Python调用环境:

source activate <env name>

在必须处理不同版本的Python的情况下,此功能似乎特别有用。

而且,conda具有以下功能:

  • 不可知的Python
  • 跨平台
  • 无需管理员权限
  • 智能依赖性管理(通过SAT求解器)
  • 很好地处理了您可能必须链接的C,Fortran和系统级库

如果您身处科学计算领域,那么最后一点尤其重要。

Updating this question in late 2014 where fortunately the Python packaging chaos has been greatly cleaned up by Continuum’s “conda” package manager.

In particular, conda quickly enables the creation of conda “environments“. You can configure your environments with different versions of Python. For example:

conda create -n py34 python=3.4 anaconda

conda create -n py26 python=2.6 anaconda

will create two (“py34” or “py26”) Python environments with different versions of Python.

Afterwards you can invoke the environment with the specific version of Python with:

source activate <env name>

This feature seems especially useful in your case where you are having to deal with different version of Python.

Moreover, conda has the following features:

  • Python agnostic
  • Cross platform
  • No admin privileges required
  • Smart dependency management (by way of a SAT solver)
  • Nicely deals with C, Fortran and system level libraries that you may have to link against

That last point is especially important if you are in the scientific computing arena.


如何使用Python 3安装pip?

问题:如何使用Python 3安装pip?

我要安装pip。它应支持Python 3,但需要setuptools,该工具仅适用于Python 2。

如何使用Python 3安装pip?

I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.

How can I install pip with Python 3?


回答 0

编辑:手动安装和使用setuptools不再是标准过程。

如果您运行的是Python 2.7.9+或Python 3.4+

恭喜,您应该已经pip安装了。如果您不这样做,请继续阅读。

如果您正在运行类似Unix的系统

pip如果您的Python版本低于2.7.9或3.4,或者您的系统出于任何原因未包含该软件包,通常可以通过软件包管理器进行安装。

以下是一些更常见发行版的说明。

在适用于Python 2.x的Debian(Wheezy和更高版本)和Ubuntu(Trusty Tahr和更高版本)上安装

从终端运行以下命令:

sudo apt-get install python-pip 

在适用于Python 3.x的Debian(Wheezy和更高版本)和Ubuntu(Trusty Tahr和更高版本)上安装

从终端运行以下命令:

sudo apt-get install python3-pip
注意:

在全新安装的Debian / Ubuntu中,只有在执行以下操作后才能找到该软件包:

sudo apt-get update

pip在适用于Python 2.x的CentOS 7上安装

在CentOS 7上,您必须先安装设置工具,然后再使用它来安装pip,因为它没有直接的软件包。

sudo yum install python-setuptools
sudo easy_install pip

pip在适用于Python 3.x的CentOS 7上安装

假设您从EPEL安装了Python 3.4 ,则可以安装Python 3的设置工具并使用它进行安装pip

# First command requires you to have enabled EPEL for CentOS7
sudo yum install python34-setuptools
sudo easy_install pip

如果您的Unix / Linux发行版未在软件包repos中包含它

使用下面详细介绍的手动方法进行安装。

手动方式

如果您想手动进行操作,现在推荐的方法是使用安装说明中get-pip.py脚本进行pip安装

安装点子

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

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

python get-pip.py 

如果setuptools尚未安装,get-pip.py将为您安装setuptools。

edit: Manual installation and use of setuptools is not the standard process anymore.

If you’re running Python 2.7.9+ or Python 3.4+

Congrats, you should already have pip installed. If you do not, read onward.

If you’re running a Unix-like System

You can usually install the package for pip through your package manager if your version of Python is older than 2.7.9 or 3.4, or if your system did not include it for whatever reason.

Instructions for some of the more common distros follow.

Installing on Debian (Wheezy and newer) and Ubuntu (Trusty Tahr and newer) for Python 2.x

Run the following command from a terminal:

sudo apt-get install python-pip 

Installing on Debian (Wheezy and newer) and Ubuntu (Trusty Tahr and newer) for Python 3.x

Run the following command from a terminal:

sudo apt-get install python3-pip
Note:

On a fresh Debian/Ubuntu install, the package may not be found until you do:

sudo apt-get update

Installing pip on CentOS 7 for Python 2.x

On CentOS 7, you have to install setup tools first, and then use that to install pip, as there is no direct package for it.

sudo yum install python-setuptools
sudo easy_install pip

Installing pip on CentOS 7 for Python 3.x

Assuming you installed Python 3.4 from EPEL, you can install Python 3’s setup tools and use it to install pip.

# First command requires you to have enabled EPEL for CentOS7
sudo yum install python34-setuptools
sudo easy_install pip

If your Unix/Linux distro doesn’t have it in package repos

Install using the manual way detailed below.

The manual way

If you want to do it the manual way, the now-recommended method is to install using the get-pip.py script from pip‘s installation instructions.

Install pip

To install pip, securely download get-pip.py

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

python get-pip.py 

If setuptools is not already installed, get-pip.py will install setuptools for you.


回答 1

我可以通过运行Ubuntu在python 3上安装pip sudo apt-get install python3-pip

I was able to install pip for python 3 on Ubuntu just by running sudo apt-get install python3-pip.


回答 2

Python 3.4以上和Python 2.7.9以上

好消息!Pip随附了Python 3.4(2014年3月发布)。这是所有Python版本中的最佳功能。它使每个人都可以访问社区丰富的图书馆。新手不再因安装的困难而被排除在外。在与软件包管理器一起交付时,Python加入了Ruby,Nodejs,Haskell,Perl,Go以及几乎所有其他具有主流开源社区的当代语言。谢谢Python。

当然,这并不意味着Python打包已解决问题。经验仍然令人沮丧。我在Python是否有软件包/模块管理系统中讨论了这一点

las惜使用早期Python的每个人。遵循手册说明。

Python≤2.7.8和Python≤3.3

按照我的详细说明在 https://stackoverflow.com/a/12476379/284795。实质上

官方指示

根据https://pip.pypa.io/en/stable/installing.html

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

python get-pip.py

您可能需要管理员命令提示符才能执行此操作。遵循http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx

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

pip install httpie

你去了(希望)!

Python 3.4+ and Python 2.7.9+

Good news! Python 3.4 (released March 2014) ships 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 by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Nodejs, Haskell, Perl, Go–almost every other contemporary language with a majority open-source community. Thank you Python.

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

Alas for everyone using an earlier Python. Manual instructions follow.

Python ≤ 2.7.8 and Python ≤ 3.3

Follow my detailed instructions at https://stackoverflow.com/a/12476379/284795 . Essentially

Official instructions

Per https://pip.pypa.io/en/stable/installing.html

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 http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx

For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (eg. 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)!


回答 3

对于Ubuntu 12.04或更旧版本,

sudo apt-get install python3-pip

将无法正常工作。而是使用:

sudo apt-get install python3-setuptools ca-certificates
sudo easy_install3 pip

For Ubuntu 12.04 or older,

sudo apt-get install python3-pip

won’t work. Instead, use:

sudo apt-get install python3-setuptools ca-certificates
sudo easy_install3 pip

回答 4

如果您使用的是python 3.4+

只需输入:

python3 -m pip

if you’re using python 3.4+

just type:

python3 -m pip

回答 5

2015年1月20日更新:

根据https://pip.pypa.io/en/latest/installing.html,当前方式为:

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

我认为这适用于任何版本


原始答案:

wget http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

Update 2015-01-20:

As per https://pip.pypa.io/en/latest/installing.html the current way is:

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

I think that should work for any version


Original Answer:

wget http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

回答 6

系统中的单个Python

要在Python中安装软件包,请始终遵循以下步骤:

  1. 如果包装是用于python 2.xsudo python -m pip install [package]
  2. 如果包装是用于python 3.xsudo python3 -m pip install [package]

注意:这是假设未为设置别名 python

通过这种方法,将不会混淆哪个Python版本正在接收该软件包。

多个Python

假设你有python3 ↔ python3.6python3.7 ↔ python3.7

  1. 要安装python3.6sudo python3 -m pip install [package]
  2. 要安装python3.7sudo python3.7 -m pip install [package]

这基本上与前面显示的方法相同。

注1

如何找到您的python3命令产生的python :

ganesh@Ganesh:~$ python3 # Type in terminal
Python 3.6.6 (default, Sep 12 2018, 18:26:19) # Your python3 version
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

注意第二行中的python 3.6.6

笔记2

更改python3python指向以下内容:https : //askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3

Single Python in system

To install packages in Python always follow these steps:

  1. If the package is for python 2.x: sudo python -m pip install [package]
  2. If the package is for python 3.x: sudo python3 -m pip install [package]

Note: This is assuming no alias is set for python

Through this method, there will be no confusion regarding which python version is receiving the package.

Multiple Pythons

Say you have python3 ↔ python3.6 and python3.7 ↔ python3.7

  1. To install for python3.6: sudo python3 -m pip install [package]
  2. To instal for python3.7: sudo python3.7 -m pip install [package]

This is essentially the same method as shown previously.

Note 1

How to find which python, your python3 command spawns:

ganesh@Ganesh:~$ python3 # Type in terminal
Python 3.6.6 (default, Sep 12 2018, 18:26:19) # Your python3 version
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Notice python 3.6.6 in the second line.

Note 2

Change what python3 or python points to: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3


回答 7

python3 -m ensurepip

我不确定何时确切引入此功能,但尚不存在时会为我安装pip3。

python3 -m ensurepip

I’m not sure when exactly this was introduced, but it’s installed pip3 for me when it didn’t already exist.


回答 8

旧版的Homebrew

如果您使用的是macOS,请使用homebrew

brew install python3 # this installs python only
brew postinstall python3 # this command 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>

Older version of Homebrew

If you are on macOS, use homebrew.

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

Also note that you should check the console if the install finished successfully. Sometimes it doesn’t (e.g. an error due to ownership), but people simply overlook the log.


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>.


回答 9

如果您使用多个不同版本的python,请尝试使用virtualenv http://www.virtualenv.org/en/latest/virtualenv.html#installation

具有pip针对每个本地环境的优势。

然后通过以下方式在当前目录中安装本地环境:

virtualenv -p /usr/local/bin/python3.3 ENV --verbose

请注意,您指定了系统上已安装的python二进制文件的路径。

然后在该文件夹中有一个本地pythonenvironment。 ./ENV

现在应该有 ./ENV/pip-3.3

用于 ./ENV/pip-3.3 freeze列出本地安装的库。

用于./ENV/pip-3.3 install packagename在本地环境中安装。

用于./ENV/python3.3 pythonfile.py运行您的python脚本。

If you use several different versions of python try using virtualenv http://www.virtualenv.org/en/latest/virtualenv.html#installation

With the advantage of pip for each local environment.

Then install a local environment in the current directory by:

virtualenv -p /usr/local/bin/python3.3 ENV --verbose

Note that you specify the path to a python binary you have installed on your system.

Then there are now an local pythonenvironment in that folder. ./ENV

Now there should be ./ENV/pip-3.3

use ./ENV/pip-3.3 freeze to list the local installed libraries.

use ./ENV/pip-3.3 install packagename to install at the local environment.

use ./ENV/python3.3 pythonfile.py to run your python script.


回答 10

这是我在ubuntu 12.04上解决此问题的方法:

sudo apt-get install build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev

然后从源代码安装python3:

wget https://www.python.org/ftp/python/3.4.0/Python-3.4.0.tar.xz
tar xvf Python-3.4.0.tar.xz
cd Python-3.4.0
./configure
make
make test
sudo make install

当您全部安装完后,pip3将自动安装。

Here is my way to solve this problem at ubuntu 12.04:

sudo apt-get install build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev

Then install the python3 from source code:

wget https://www.python.org/ftp/python/3.4.0/Python-3.4.0.tar.xz
tar xvf Python-3.4.0.tar.xz
cd Python-3.4.0
./configure
make
make test
sudo make install

When you finished installing all of them, pip3 will get installed automatically.


回答 11

这就是我在OS X Mavericks上所做的工作,以使其正常工作。

首先,冲泡安装了

安装python 3.4

brew install python3

然后,我得到了最新版本的distribution:

wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a

unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo setup.py install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper

mkvirtualenv py3 

python --version
Python 3.4.1

我希望这有帮助。

This is what I did on OS X Mavericks to get this to work.

Firstly, have brew installed

Install python 3.4

brew install python3

Then I get the latest version of distribute:

wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a

unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo setup.py install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper

mkvirtualenv py3 

python --version
Python 3.4.1

I hope this helps.


回答 12

Python 3.4新增功能

点子应该总是可用

默认情况下,命令pipX和pipX.Y将连同pip Python软件包及其依赖项一起安装在所有平台上(其中XY代表Python安装的版本)。

https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453

因此,如果您安装了python 3.4,则可以: sudo pip3 install xxx

What’s New In Python 3.4

pip should always be available

By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.

https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453

so if you have python 3.4 installed, you can just: sudo pip3 install xxx


回答 13

对于python3,请尝试以下操作:

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python

好消息是它还将检测您拥有的python版本(即使它是您自定义位置中的python环境)。之后,您可以正常进行操作(例如)

pip install numpy

资源: https //pypi.python.org/pypi/setuptools/1.1.6#upgrading-from-setuptools-0-6

For python3 try this:

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python

The good thing is that It will also detect what version of python you have (even if it’s an environment of python in your custom location). After this you can proceed normally with (for example)

pip install numpy

source: https://pypi.python.org/pypi/setuptools/1.1.6#upgrading-from-setuptools-0-6


回答 14

假设您处于高度受限的计算机环境中(例如我本人),而没有root访问权限或无法安装软件包…

在发布本文之前,我从未设置过Python / virtualenv的新/独立/原始/非根实例。我已经做了很多谷歌搜索工作。

  1. 确定您使用的是python(python2)还是python3,并正确设置PATH。(我严格是python3用户。)如果您是python2用户python3python则下面的所有命令都可以代替。
  2. wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
  3. tar -xzvf virtualenv-x.y.z.tar.gz
  4. python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
  5. source /path/to/new/virtualenv/bin/activate
    • 假设您使用的是兼容Bourne的外壳,例如bash
    • 出色的是,此virtualenv软件包包括的独立版本,pip并且setuptools会自动神奇地安装到每个新的virtualenv中。这解决了鸡肉和鸡蛋的问题。
    • 您可能想为此最终命令创建一个别名(或更新〜/ .bashrc等),以在每次登录时激活python virtualenv。记住所有这些路径和命令可能很痛苦。
  6. 现在检查您的python版本:which python3应该给出:/path/to/new/virtualenv/bin/python3
  7. pip也可以通过以下命令在virtualenv中进行检查which pip:应该给出:/path/to/new/virtualenv/bin/pip

然后…点,点,点!

给新手Pythoneers的最后提示:开始时您不需要虚拟环境,但是以后会很高兴的。帮助开源/共享软件包的“假设情况”安装/升级方案。

参考:https : //virtualenv.pypa.io/en/latest/installation.html

Assuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages…

I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post. I had do quite a bit of Googling to make this work.

  1. Decide if you are using python (python2) or python3 and set your PATH correctly. (I am strictly a python3 user.) All commands below can substitute python3 for python if you are python2 user.
  2. wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
  3. tar -xzvf virtualenv-x.y.z.tar.gz
  4. python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
  5. source /path/to/new/virtualenv/bin/activate
    • Assumes you are using a Bourne-compatible shell, e.g., bash
    • Brilliantly, this virtualenv package includes a standalone version of pip and setuptools that are auto-magically installed into each new virtualenv. This solves the chicken and egg problem.
    • You may want to create an alias (or update your ~/.bashrc, etc.) for this final command to activate the python virtualenv during each login. It can be a pain to remember all these paths and commands.
  6. Check your version of python now: which python3 should give: /path/to/new/virtualenv/bin/python3
  7. Check pip is also available in the virtualenv via which pip… should give: /path/to/new/virtualenv/bin/pip

Then… pip, pip, pip!

Final tip to newbie Pythoneers: You don’t think you need virtualenv when you start, but you will be happy to have it later. Helps with “what if” installation / upgrade scenarios for open source / shared packages.

Ref: https://virtualenv.pypa.io/en/latest/installation.html


回答 15

pip在您安装Python时一起安装。您可以使用 sudo pip install (module)python3 -m pip install (module)

pip is installed together when you install Python. You can use sudo pip install (module) or python3 -m pip install (module).


回答 16

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

然后运行以下命令:

python get-pip.py

如果您使用的是由操作系统或其他程序包管理器管理的Python安装,请务必谨慎。get-pip.py与这些工具不协调,可能会使您的系统处于不一致状态。

参考:PIP安装

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

Then run the following:

python get-pip.py

Be cautious if you’re using a Python install that’s managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.

Refer: PIP Installation


回答 17

对于Windows 8.1 / 10 OS用户,只需打开 cmd(命令提示符)

写这个: C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts

然后

只需这样写:pip3 install{软件包名称}

提示:Python36-32对于新的python 3.x版本,文件夹的位置可能会有所不同

And for Windows 8.1/10 OS Users just open cmd (command prompt)

write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts

then

just write this : pip3 install {name of package}

Hint: the location of folder Python36-32 may get different for new python 3.x versions


回答 18

如果您的Linux发行版中已经安装了Python,则应该可以使用系统的软件包管理器来安装PIP。这是可取的,因为系统安装的Python版本无法与Windows和Mac上使用的get-pip.py脚本很好地配合使用。

高级打包工具(Python 2.x)

sudo apt-get install python-pip

进阶套件工具(Python 3.x)

sudo apt-get install python3-pip

pacman软件包管理器(Python 2.x)

sudo pacman -S python2-pip

pacman软件包管理器(Python 3.x)

sudo pacman -S python-pip

Yum软件包管理器(Python 2.x)

sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel

Yum软件包管理器(Python 3.x)

sudo yum install python3 python3-wheel

Dandified Yum(Python 2.x)

sudo dnf upgrade python-setuptools
sudo dnf install python-pip python-wheel

Dandified Yum(Python 3.x)

sudo dnf install python3 python3-wheel

Zypper软件包管理器(Python 2.x)

sudo zypper install python-pip python-setuptools python-wheel

Zypper软件包管理器(Python 3.x)

sudo zypper install python3-pip python3-setuptools python3-wheel

If your Linux distro came with Python already installed, you should be able to install PIP using your system’s package manager. This is preferable since system-installed versions of Python do not play nicely with the get-pip.py script used on Windows and Mac.

Advanced Package Tool (Python 2.x)

sudo apt-get install python-pip

Advanced Package Tool (Python 3.x)

sudo apt-get install python3-pip

pacman Package Manager (Python 2.x)

sudo pacman -S python2-pip

pacman Package Manager (Python 3.x)

sudo pacman -S python-pip

Yum Package Manager (Python 2.x)

sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel

Yum Package Manager (Python 3.x)

sudo yum install python3 python3-wheel

Dandified Yum (Python 2.x)

sudo dnf upgrade python-setuptools
sudo dnf install python-pip python-wheel

Dandified Yum (Python 3.x)

sudo dnf install python3 python3-wheel

Zypper Package Manager (Python 2.x)

sudo zypper install python-pip python-setuptools python-wheel

Zypper Package Manager (Python 3.x)

sudo zypper install python3-pip python3-setuptools python3-wheel

回答 19

请按照以下步骤使用pip安装python 3:

步骤1:从此处下载安装Python

步骤2:您需要下载 get-pip.py

步骤3:下载get-pip.py之后,打开命令提示符,然后转到保存get-pip.py文件的目录。

步骤4:输入命令 python get-pip.py在cmd中。

步骤5:Pip安装成功,通过cmd中的type命令验证pip安装 pip --version

Please follow below steps to install python 3 with pip:

Step 1 : Install Python from download here

Step 2 : you’ll need to download get-pip.py

Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .

Step 4 : Enter command python get-pip.py in cmd.

Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version


回答 20

这是我复制粘贴的单线。

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

使用get-pip.py安装

要安装pip,请get-pip.py通过以下链接安全下载: get-pip.py。或者,使用curl:

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

然后在下载了get-pip.py的文件夹中运行以下命令:

python get-pip.py

警告:如果您使用的是由操作系统或其他程序包管理器管理的Python安装,请务必谨慎。get-pip.py与这些工具不协调,可能会使您的系统处于不一致状态。

This is the one-liner I copy-and-paste.

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

From Installing with get-pip.py:

To install pip, securely download get-pip.py by following this link: get-pip.py. Alternatively, use curl:

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

Then run the following command in the folder where you have downloaded get-pip.py:

python get-pip.py

Warning: Be cautious if you are using a Python install that is managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.


没有名为pkg_resources的模块

问题:没有名为pkg_resources的模块

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

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

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

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

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

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

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

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

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

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

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

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


回答 0

2018年7月更新

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

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

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

说明

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

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

旧版答案

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

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

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

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

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

可能带有sudo前缀。)

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

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


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

July 2018 Update

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

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

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

Explanation

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

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

Legacy Answer

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

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

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

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

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

possibly with sudo prepended.)

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

See Installation Instructions for further details.


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


回答 1

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

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

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

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


回答 2

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

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

在运行easy_install rhodecode之前。

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

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

before I run easy_install rhodecode.


回答 3

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

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

如果使用virtualenvwrapper的示例:

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

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

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

An example if using virtualenvwrapper:

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

回答 4

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

yum install python-setuptools

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

yum install python-setuptools

回答 5

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

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

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

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

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

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

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

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

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

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

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

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


回答 6

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

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

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

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

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

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


回答 7

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

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

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

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

回答 8

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

从复制了pkg_resources.py

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

/Library/Python/2.7/site-packages/

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

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

I fixed the error with virtualenv by doing this:

Copied pkg_resources.py from

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

to

/Library/Python/2.7/site-packages/

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

.

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


回答 9

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

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

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

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

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

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

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

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


回答 10

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

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

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

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

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

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


回答 11

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

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

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

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


回答 12

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

运行的命令是:

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

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

Command to run is:

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

回答 13

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

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

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

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

回答 14

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

conda install setuptools

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

conda install setuptools

回答 15

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

pip install --upgrade setuptools --user

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

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

pip install --upgrade setuptools --user

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


回答 16

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

conda upgrade -c anaconda setuptools

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

conda install -c anaconda setuptools

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

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

conda upgrade -c anaconda setuptools

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

conda install -c anaconda setuptools

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


回答 17

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

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


回答 18

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

virtualenv venv

指的是卸载的python

什么对我有用

python3 -m virtualenv venv

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

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

virtualenv venv

was referring to the uninstalled python

What worked for me

python3 -m virtualenv venv

Same is true when you are trying to use pip.


回答 19

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

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


回答 20

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

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

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

So I should have installed setuptools(easy_install) first.


回答 21

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

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

那么一切都会好起来的。

just reinstall your setuptools by :

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

then everything will be fine.


回答 22

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

sudo yum install python-devel

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

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

sudo yum install python-devel

Hope help someone in the same situation.


回答 23

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

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

sudo easy_install pip 

pip install --upgrade setuptools

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

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

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

sudo easy_install pip 

pip install --upgrade setuptools

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


回答 24

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

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

例如:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

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

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

e.g.:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

回答 25

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

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


回答 26

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

zypper in python-Pygments

On Opensuse 42.1 the following fixed this issue:

zypper in python-Pygments

回答 27

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

步骤:1登录到root用户。

sudo su root

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

apt-get purge -y python-pip

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

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

步骤:4运行python文件。

python ./get-pip.py

步骤:5 Finalic exicute安装命令。

apt-get install python-pip

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

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

Step: 1 Login in root user.

sudo su root

Step: 2 Uninstall python-pip package if existing.

apt-get purge -y python-pip

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

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

Step: 4 Run python file.

python ./get-pip.py

Step: 5 Finaly exicute installation command.

apt-get install python-pip

Note: User must be root.


回答 28

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

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


回答 29

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

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


为什么要在easy_install上使用pip?[关闭]

问题:为什么要在easy_install上使用pip?[关闭]

一条推文中写道:

不要使用easy_install,除非您喜欢对自己的脸部进行刺伤。使用点子。

为什么要在easy_install上使用pip?难道不是PyPI和程序包作者最主要的原因吗?如果作者将废话源tarball(例如:缺少文件,没有setup.py)上传到PyPI,则pip和easy_install都将失败。除了化妆品的差异,为什么Python的人(如上面的鸣叫)似乎强烈地倾向于在点子的easy_install?

(假设我们正在谈论由社区维护的Distribute软件包中的easy_install)

A tweet reads:

Don’t use easy_install, unless you like stabbing yourself in the face. Use pip.

Why use pip over easy_install? Doesn’t the fault lie with PyPI and package authors mostly? If an author uploads crap source tarball (eg: missing files, no setup.py) to PyPI, then both pip and easy_install will fail. Other than cosmetic differences, why do Python people (like in the above tweet) seem to strongly favor pip over easy_install?

(Let’s assume that we’re talking about easy_install from the Distribute package, that is maintained by the community)


回答 0

此处的许多答案在2015年已经过时了(尽管最初由Daniel Roseman接受的答案不是)。这是当前的状态:

  • 现在,二进制程序包以轮子(.whl文件)的形式分发-不仅在PyPI上,而且在第三方存储库中,例如Christoph Gohlke的Windows Extension Packagespip可以处理轮子;easy_install不能。
  • 虚拟环境(由3.4内置,或者可以通过2.6添加到2.6 + / 3.1 + virtualenv)已经成为一个非常重要和突出的工具(并在官方文档中推荐);它们pip是开箱即用的,但是甚至无法正常使用easy_install
  • distribute包含的软件包easy_install不再维护。它的改进已setuptools合并回setuptools。尝试安装distribute只会安装setuptools
  • easy_install 本身只是准维护的。
  • 所有的其中箱子pip用于不如easy_install从解包源树-installing,从DVCS回购等-是早已过去的; 你可以pip install .pip install git+https://
  • pip带有来自python.org的官方Python 2.7和3.4+软件包,pip如果您从源代码构建,则默认情况下会包含引导程序。
  • Python打包用户指南》已取代了有关安装,使用和构建软件包的各种文档的不完整之处。现在,Python自己的有关安装Python模块的文档符合该用户指南的要求,并明确地pip称为“首选安装程序”。
  • pip这些年来,还添加了其他新功能,这些功能将永远不会存在easy_install。例如,pip通过构建需求文件,然后在每一侧使用单个命令安装它,可以轻松克隆站点程序包。或将您的需求文件转换为本地回购以用于内部开发。等等。

我知道easy_install在2015年使用的唯一好的理由是在OS X 10.5-10.8中使用Apple预先安装的Python版本的特殊情况。从10.5开始,Apple已包含easy_install,但从10.10开始,它们仍然不包含pip。使用10.9+时,您仍然应该只使用get-pip.py,但是对于10.5-10.8,这存在一些问题,因此更容易实现sudo easy_install pip。(通常,这easy_install pip是一个坏主意;您只想在OS X 10.5-10.8上才能做到这一点。)此外,10.5-10.8包含readline以一种easy_install知道如何纠缠而pip不会纠缠的方式,因此您也想sudo easy_install readline如果要升级。

Many of the answers here are out of date for 2015 (although the initially accepted one from Daniel Roseman is not). Here’s the current state of things:

  • Binary packages are now distributed as wheels (.whl files)—not just on PyPI, but in third-party repositories like Christoph Gohlke’s Extension Packages for Windows. pip can handle wheels; easy_install cannot.
  • Virtual environments (which come built-in with 3.4, or can be added to 2.6+/3.1+ with virtualenv) have become a very important and prominent tool (and recommended in the official docs); they include pip out of the box, but don’t even work properly with easy_install.
  • The distribute package that included easy_install is no longer maintained. Its improvements over setuptools got merged back into setuptools. Trying to install distribute will just install setuptools instead.
  • easy_install itself is only quasi-maintained.
  • All of the cases where pip used to be inferior to easy_install—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can pip install ., pip install git+https://.
  • pip comes with the official Python 2.7 and 3.4+ packages from python.org, and a pip bootstrap is included by default if you build from source.
  • The various incomplete bits of documentation on installing, using, and building packages have been replaced by the Python Packaging User Guide. Python’s own documentation on Installing Python Modules now defers to this user guide, and explicitly calls out pip as “the preferred installer program”.
  • Other new features have been added to pip over the years that will never be in easy_install. For example, pip makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.

The only good reason that I know of to use easy_install in 2015 is the special case of using Apple’s pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included easy_install, but as of 10.10 they still don’t include pip. With 10.9+, you should still just use get-pip.py, but for 10.5-10.8, this has some problems, so it’s easier to sudo easy_install pip. (In general, easy_install pip is a bad idea; it’s only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include readline in a way that easy_install knows how to kludge around but pip doesn’t, so you also want to sudo easy_install readline if you want to upgrade that.


回答 1

从伊恩·比金(Ian Bicking)自己对pip介绍

pip最初旨在通过以下方式对easy_install进行改进

  • 所有软件包均在安装前已下载。结果不会发生部分完成的安装。
  • 注意在控制台上显示有用的输出。
  • 采取行动的原因已被跟踪。例如,如果正在安装软件包,则pip会跟踪为什么需要该软件包。
  • 错误消息应该很有用。
  • 该代码相对简洁明了,具有内聚性,可以更轻松地以编程方式使用。
  • 软件包不必作为Egg存档安装,可以将它们平放安装(同时保留Egg元数据)。
  • 对其他版本控制系统(Git,Mercurial和Bazaar)的本地支持
  • 卸载软件包。
  • 简单定义固定的需求集并可靠地复制一组包。

From Ian Bicking’s own introduction to pip:

pip was originally written to improve on easy_install in the following ways

  • All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
  • Care is taken to present useful output on the console.
  • The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
  • Error messages should be useful.
  • The code is relatively concise and cohesive, making it easier to use programmatically.
  • Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
  • Native support for other version control systems (Git, Mercurial and Bazaar)
  • Uninstallation of packages.
  • Simple to define fixed sets of requirements and reliably reproduce a set of packages.

回答 2

另一个(至今尚未提及)之所以喜欢点子,是因为它是新的热点,并将在未来继续使用。

以下信息图表(来自《The Hitchhiker’s Guide to Packaging v1.0》中的包装当前状态”部分)表明setuptools / easy_install将来会消失。

这是Distribution的文档中的另一个信息图,显示Setuptools和easy_install将被新的热点— distributionpip取代。虽然PIP仍然是新的辣味,分发与合并的setuptools在2013年发布的setuptools V0.7。

Another—as of yet unmentioned—reason for favoring pip is because it is the new hotness and will continue to be used in the future.

The infographic below—from the Current State of Packaging section in the The Hitchhiker’s Guide to Packaging v1.0—shows that setuptools/easy_install will go away in the future.

Here’s another infographic from distribute’s documentation showing that Setuptools and easy_install will be replaced by the new hotness—distribute and pip. While pip is still the new hotness, Distribute merged with Setuptools in 2013 with the release of Setuptools v0.7.


回答 3

有两个原因,可能还有更多:

  1. pip提供uninstall命令

  2. 如果中间安装失败,则pip将使您保持干净状态。

Two reasons, there may be more:

  1. pip provides an uninstall command

  2. if an installation fails in the middle, pip will leave you in a clean state.


回答 4

需求文件。

认真地说,我每天都将它与virtualenv结合使用。


快速依赖管理教程,民谣

需求文件使您可以创建已通过pip安装的所有软件包的快照。通过将这些程序包封装在虚拟环境中,可以使代码库在一组非常特定的程序包中工作,并与其他人共享该代码库。

从Heroku的文档中 https://devcenter.heroku.com/articles/python

您创建一个虚拟环境,并设置您的外壳以使用它。(bash / * nix指令)

virtualenv env
source env/bin/activate

现在,与此外壳一起运行的所有python脚本都将使用该环境的软件包和配置。现在,您可以在此环境中本地安装软件包,而无需在计算机上全局安装。

pip install flask

现在,您可以转储有关安装哪些软件包的信息

pip freeze > requirements.txt

如果您将该文件签入版本控制中,那么当其他人获取您的代码时,他们可以设置自己的虚拟环境并使用以下命令安装所有依赖项:

pip install -r requirements.txt

任何时候您都可以像这样自动执行乏味的操作。

REQUIREMENTS files.

Seriously, I use this in conjunction with virtualenv every day.


QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS

Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.

From Heroku’s documentation https://devcenter.heroku.com/articles/python

You create a virtual environment, and set your shell to use it. (bash/*nix instructions)

virtualenv env
source env/bin/activate

Now all python scripts run with this shell will use this environment’s packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.

pip install flask

Now you can dump the info about which packages are installed with

pip freeze > requirements.txt

If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:

pip install -r requirements.txt

Any time you can automate tedium like this is awesome.


回答 5

pip不会安装二进制软件包,并且未在Windows上经过良好测试。

由于Windows默认没有附带编译器,因此通常无法在其中使用pip 。easy_install 可以为Windows安装二进制软件包。

pip won’t install binary packages and isn’t well tested on Windows.

As Windows doesn’t come with a compiler by default pip often can’t be used there. easy_install can install binary packages for Windows.


回答 6

更新:正如某些人所想,setuptools已经吸收distribute了相反的东西。setuptools是最新的最新distutils更改和滚轮格式。因此,easy_installpip或多或少平等现在。

来源:http : //pythonhosted.org/setuptools/merge-faq.html#why-setuptools-and-not-distribute-or-another-name

UPDATE: setuptools has absorbed distribute as opposed to the other way around, as some thought. setuptools is up-to-date with the latest distutils changes and the wheel format. Hence, easy_install and pip are more or less on equal footing now.

Source: http://pythonhosted.org/setuptools/merge-faq.html#why-setuptools-and-not-distribute-or-another-name


回答 7

除了模糊人的答复:

pip不会安装二进制软件包,并且未在Windows上经过良好测试。

由于Windows默认不带编译器,因此通常无法在其中使用pip。easy_install可以为Windows安装二进制软件包。

这是Windows上的一个技巧:

  • 您可以使用easy_install <package>安装二进制软件包来避免生成二进制文件

  • pip uninstall <package>即使您使用过easy_install,也可以使用 。

这只是在Windows上对我有效的解决方法。实际上,如果不涉及二进制文件,我总是使用pip。

请参阅当前的pip doku:http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

我将在邮件列表中询问为此计划的内容。

这是最新的更新:

新的受支持的安装二进制文件的方式将是wheel!它尚未在标准中,但几乎已经存在。当前版本仍为Alpha:1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

我将wheel通过创建要PySide使用的OS X安装程序进行测试wheel,而不是蛋。会回来并报告此情况。

欢呼声-克里斯

快速更新:

到的过渡wheel即将结束。大多数软件包都支持wheel

我答应为制作车轮PySide,去年夏天我做了。很棒!

提示:一些开发商至今未能支撑轮格式,仅仅是因为他们忘记更换distutilssetuptools。通常,通过替换中的单个单词很容易转换此类软件包setup.py

As an addition to fuzzyman’s reply:

pip won’t install binary packages and isn’t well tested on Windows.

As Windows doesn’t come with a compiler by default pip often can’t be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers – Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.


回答 8

刚遇到一个我不得不easy_install代替的特殊情况pip,否则我必须直接提取源代码。

对于该软件包GitPython,in中的版本pip太旧,即0.1.7,而from中的版本easy_install是最新的,即0.3.2.rc1

我正在使用Python 2.7.8。我不知道有关的底层机制easy_installpip,但至少有一些包的版本可能是彼此不同的,有时easy_install是一个较新的版本。

easy_install GitPython

Just met one special case that I had to use easy_install instead of pip, or I have to pull the source codes directly.

For the package GitPython, the version in pip is too old, which is 0.1.7, while the one from easy_install is the latest which is 0.3.2.rc1.

I’m using Python 2.7.8. I’m not sure about the underlay mechanism of easy_install and pip, but at least the versions of some packages may be different from each other, and sometimes easy_install is the one with newer version.

easy_install GitPython

如何删除使用Python的easy_install安装的软件包?

问题:如何删除使用Python的easy_install安装的软件包?

Python easy_install使安装新软件包非常方便。但是,据我所知,它没有实现依赖项管理器的其他常见功能-列出和删除已安装的软件包。

找出已安装的软件包的最佳方法是什么,以及删除已安装软件包的首选方法是什么?如果我手动(例如,通过rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg类似方式)删除软件包,是否需要更新任何文件?

Python’s easy_install makes installing new packages extremely convenient. However, as far as I can tell, it doesn’t implement the other common features of a dependency manager – listing and removing installed packages.

What is the best way of finding out what’s installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg or similar)?


回答 0

pip是setuptools / easy_install的替代产品,提供了“卸载”命令。

根据安装说明安装pip :

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

然后,您可以使用pip uninstall删除与easy_install

pip, an alternative to setuptools/easy_install, provides an “uninstall” command.

Install pip according to the installation instructions:

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

Then you can use pip uninstall to remove packages installed with easy_install


回答 1

要卸载,.egg您需要rm -rf鸡蛋(可能是目录)并从中删除匹配的行site-packages/easy-install.pth

To uninstall an .egg you need to rm -rf the egg (it might be a directory) and remove the matching line from site-packages/easy-install.pth


回答 2

首先,您必须运行以下命令:

$ easy_install -m [PACKAGE]

它删除了程序包的所有依赖项。

然后删除该包装的鸡蛋文件:

$ sudo rm -rf /usr/local/lib/python2.X/site-packages/[PACKAGE].egg

First you have to run this command:

$ easy_install -m [PACKAGE]

It removes all dependencies of the package.

Then remove egg file of that package:

$ sudo rm -rf /usr/local/lib/python2.X/site-packages/[PACKAGE].egg

回答 3

所有的信息在其他的答案,但没有总结两者的请求,或者似乎使事情不必要的复杂性:

  • 对于您的搬迁需求,请使用:

    pip uninstall <package>

    (使用安装easy_install pip

  • 对于“列出已安装的软件包”,需要使用以下任一方法:

    pip freeze

    要么:

    yolk -l

    可以输出更多包装详细信息。

    (通过easy_install yolk或安装pip install yolk

All the info is in the other answers, but none summarizes both your requests or seem to make things needlessly complex:

  • For your removal needs use:

    pip uninstall <package>
    

    (install using easy_install pip)

  • For your ‘list installed packages’ needs either use:

    pip freeze
    

    Or:

    yolk -l
    

    which can output more package details.

    (Install via easy_install yolk or pip install yolk)


回答 4

网上有多个消息源建议通过使用-m选项重新安装软件包,然后仅删除lib /中的.egg文件和bin /中的二进制文件来破解。另外,可以在python bug跟踪器上找到有关setuptools问题的讨论,名称为setuptools issue 21

编辑:将链接添加到python bugtracker。

There are several sources on the net suggesting a hack by reinstalling the package with the -m option and then just removing the .egg file in lib/ and the binaries in bin/. Also, discussion about this setuptools issue can be found on the python bug tracker as setuptools issue 21.

Edit: Added the link to the python bugtracker.


回答 5

如果问题严重困扰您,您可以考虑使用virtualenv。它允许您创建一个封装python库的环境。您在此处而不是在全局site-packages目录中安装软件包。您在该环境中运行的所有脚本都可以访问这些程序包(也可以选择全局程序包)。在评估不确定/是否需要全局安装的软件包时,我经常使用此工具。如果您决定不需要该软件包,那么将虚拟环境吹走就很容易了。它很容易使用。制作一个新的环境:

$>virtualenv /path/to/your/new/ENV

virtual_envt在新环境中为您安装setuptools,因此您可以执行以下操作:

$>ENV/bin/easy_install

您甚至可以创建自己的boostrap脚本来设置新环境。因此,使用一个命令,您可以创建一个新的虚拟环境,例如默认安装了python 2.6,psycopg2和django(如果需要,您可以安装特定于环境的python版本)。

If the problem is a serious-enough annoyance to you, you might consider virtualenv. It allows you to create an environment that encapsulates python libraries. You install packages there rather than in the global site-packages directory. Any scripts you run in that environment have access to those packages (and optionally, your global ones as well). I use this a lot when evaluating packages that I am not sure I want/need to install globally. If you decide you don’t need the package, it’s easy enough to just blow that virtual environment away. It’s pretty easy to use. Make a new env:

$>virtualenv /path/to/your/new/ENV

virtual_envt installs setuptools for you in the new environment, so you can do:

$>ENV/bin/easy_install

You can even create your own boostrap scripts that setup your new environment. So, with one command, you can create a new virtual env with, say, python 2.6, psycopg2 and django installed by default (you can can install an env-specific version of python if you want).


回答 6

官方说明?:http : //peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages

如果您用其他版本替换了软件包,则可以通过删除PackageName-versioninfo.egg文件或目录(位于安装目录中)来删除不需要的软件包。

如果要删除软件包的当前安装版本(或软件包的所有版本),则应首先运行:

easy_install -mxN PackageName

这样可以确保Python不会继续搜索您打算删除的软件包。完成此操作后,您可以安全地删除.egg文件或目录以及要删除的所有脚本。

Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages

If you have replaced a package with another version, then you can just delete the package(s) you don’t need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).

If you want to delete the currently installed version of a package (or all versions of a package), you should first run:

easy_install -mxN PackageName

This will ensure that Python doesn’t continue to search for a package you’re planning to remove. After you’ve done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.


回答 7

尝试

$ easy_install -m [PACKAGE]

然后

$ rm -rf .../python2.X/site-packages/[PACKAGE].egg

try

$ easy_install -m [PACKAGE]

then

$ rm -rf .../python2.X/site-packages/[PACKAGE].egg

回答 8

要列出已安装的Python软件包,可以使用yolk -l。不过,您需要先使用easy_install yolk

To list installed Python packages, you can use yolk -l. You’ll need to use easy_install yolk first though.


回答 9

在尝试卸载随时间推移而安装的许多随机Python软件包时遇到了这个问题。

使用此线程中的信息,这是我想到的:

cat package_list | xargs -n1 sudo pip uninstall -y

package_list从清理(AWK)pip freeze中的virtualenv。

要删除几乎所有的Python软件包:

yolk -l | cut -f 1 -d " " | grep -v "setuptools|pip|ETC.." | xargs -n1 pip uninstall -y

Came across this question, while trying to uninstall the many random Python packages installed over time.

Using information from this thread, this is what I came up with:

cat package_list | xargs -n1 sudo pip uninstall -y

The package_list is cleaned up (awk) from a pip freeze in a virtualenv.

To remove almost all Python packages:

yolk -l | cut -f 1 -d " " | grep -v "setuptools|pip|ETC.." | xargs -n1 pip uninstall -y

回答 10

我在MacOS X Leopard 10.6.blah上遇到了同样的问题。

解决方案是确保您正在调用MacPorts Python:

sudo port install python26
sudo port install python_select
sudo python_select python26
sudo port install py26-mysql

希望这可以帮助。

I ran into the same problem on my MacOS X Leopard 10.6.blah.

Solution is to make sure you’re calling the MacPorts Python:

sudo port install python26
sudo port install python_select
sudo python_select python26
sudo port install py26-mysql

Hope this helps.


回答 11

对我而言,仅删除此文件:easy-install.pth有效,其余pip install django == 1.3.7

For me only deleting this file : easy-install.pth worked, rest pip install django==1.3.7


回答 12

这对我有用。它与先前的答案相似,但打包的路径不同。

  1. 须藤easy_install -m
  2. 须藤rm -rf /Library/Python/2.7/site-packages/.egg

平台:MacOS High Sierra版本10.13.3

This worked for me. It’s similar to previous answers but the path to the packages is different.

  1. sudo easy_install -m
  2. sudo rm -rf /Library/Python/2.7/site-packages/.egg

Plaform: MacOS High Sierra version 10.13.3