短的问题

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

背景

在我对SO问题4314376的回答中,我建议使用ez_setup,这样你就可以像下面这样安装pip和virtualenv:

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目录的想法,所以我在那里安装的其他包只有virtualenvwrapper和distribute。(因为这个Python公共服务公告,我最近把分发添加到我的工具箱中。为了安装这两个包,我使用了:

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

不再有setuptools和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安装任何东西。编写~/.pydistutils.cfg文件,将pip安装放在~/目录下。本地的或者其他的。特别是名为ez_setup.py的文件往往会占用setuptools和easy_install等新版本的东西,这可能会破坏操作系统上的其他东西。

回到那个简短的问题

所以,Glyph的回答让我想到了我最初的问题:

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


当前回答

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.

其他回答

你不需要在python中安装任何东西就可以做到这一点。 你不需要sudo或任何特权。 您不需要找到virtualenv tar文件的最新版本 您不需要在bash脚本中编辑版本信息以保持更新。 您不需要安装curl/wget或tar,也不需要安装pip或easy_install 这适用于2.7和3。X

将以下文件保存到“/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

并将其用作

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

例如(如果你真的需要setuptools的分发兼容层)

python /tmp/initvenv.py venv distribute

请注意,对于较旧的python版本,这可能会给你InsecurePlatformWarnings¹。

一旦你有了你的virtualenv(例如venv),你可以使用刚刚安装的virtualenv来安装另一个virtualenv:

venv/bin/virtualenv venv2

# # virtualenvwrapper

我建议在一次设置之后,看看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和/或请求中解决,但开发人员相互指向原因。我得到了一个通常不现实的建议,把我正在使用的python版本升级到最新版本。我相信这将打破例如我的Linux Mint 17安装。幸运的是,pip缓存了包,所以发出了警告 每次安装只需要一次。

Python 3.4开始

Python 3.3增加了venv模块,Python 3.4增加了ensurepip模块。这使得bootstrapping像下面这样简单:

Python -m ensurepip

可能在虚拟环境中调用venv来执行此操作。

PEP 453中描述了保证pip。

下面是一种安装virtualenvwrapper的好方法。

下载virtualenv-1.11.4(你可以在这里找到最新版本),解压,打开终端

# 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 env1, lsvirtualenv ..等

注意:可以在“下载”文件夹中删除virtualenv-1.11.4和virtualenv-1.11.4.zip。

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.

更新:截至2013年7月,该项目不再维护。作者建议使用pyenv。(pyenv没有内置对virtualenv的支持,但使用起来很不错。)

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

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

# Initializes the virtualenv 
pythonbrew venv init

# Create a virtual/sandboxed environment 
pythonbrew venv create mycoolbundle  

# Use it 
pythonbrew venv use mycoolbundle