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:

  • Matthew, I know this thread is rather old. But is there anything new on this front? Is it still a bad idea to do python distribute_setup.py followed by easy_install pip and virtualenv --distribute venv? (see python-guide.readthedocs.org/en/latest/starting/install/…), and if so, why? – Amelio Vazquez-Reina Apr 18 '13 at 21:26
  • 2
    What's wrong with sudo apt-get install python-{pip,virtualenv}??? – MestreLion Aug 6 '14 at 19:17
  • 1
    Yes, generally the older-but-compatible-packages are fine when minor versions don't matter for your purposes, but you specifically asked "what's wrong with" and I'm trying to get my pedant badge. – user559633 Mar 2 '15 at 16:24
  • 1
    FYI, several links in this question are now outdated/broken - I currently (can't) see the ones to pip, virtualenv, and the Python PSA. – Chris Sprague Jan 5 '16 at 18:47
  • 1
    http://python-distribute.org/distribute_setup.py redirects to 404 :( – jitter May 1 '17 at 23:29

15 Answers 15

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
    Is ~/.local a bit of a dumb name? What if Ruby wants to do the same? Maybe ~/.python27 would be better? – Jonathan Hartley Mar 4 '11 at 10:20
  • 1
    Just a note, I just tried the same thing on Windows and had to add both the local folder (called "local" for example) and "local\Lib\site-packages" to PYTHONPATH in order to successfully run distribute_setup.py. – technomalogical Mar 14 '11 at 23:11
  • 1
    One last problem with this approach: virtualenv is incompatible with using the .pydistutils.cfg file. See github.com/pypa/virtualenv/issues/88 – user37078 May 12 '11 at 15:14
  • 3
    I think there should be an easy_install pip between step 5 and 6. – SiggyF Jun 27 '11 at 8:09
  • 5
    The ~/.local thing comes from PEP 370. – Éric Araujo Jun 30 '11 at 14:51

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.

  • 1
    Yes, I used that way. And some time later, invoking pip freeze got me almost frozen - the list of packages, being installed system wide was far too long. Since then, I strongly recommend using "no sudo" and "no os-wide" python package installation. – Jan Vlcinsky Jul 11 '13 at 19:07

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.

  • 3
    Works well. A little tedious, but does work. – user37078 May 17 '11 at 1:27
  • 12
    Tedious only because it's very generic, a simple download, untar and then python virtualenv.py TARGET_DIRECTORY does the same thing. – Sebastian Blask Jun 22 '11 at 16:21
  • 3
    This is brilliant. I adapted it to answer my more specific question about installing virtualenv across multiple versions of Python indpendently of system packages - stackoverflow.com/questions/6812207/… - works perfectly. – d3vid Jul 29 '11 at 15:12
  • 6
    note: current virtualenv don't need '--no-site-packages --distribute' options. The opposite --system-site-packages might be required – jfs Aug 9 '12 at 19:09
  • 1
    You can get the latest stable tarball with this command: curl -Lo virtualenv-tmp.tar.gz 'https://github.com/pypa/virtualenv/tarball/master' – Bohr Jul 11 '13 at 4:07

Install ActivePython. It includes pip, virtualenv and Distribute.

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.

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
  • Doesn't this install both setuptools and distribute? And doesn't that break packages like Tkinter and pyopencl that don't like setuptools? – hobs Apr 28 '13 at 19:59
  • Does setting WORKON_HOME to null in bashrc force venvwrapper to use something reasonable like export WORKON_HOME="$HOME/.virtualenvs"? – hobs Apr 28 '13 at 20:48
  • Well, it installs whatever your package manager says pip depends on. Currently, that's setuptools in Ubuntu and OS X (brew install python pulls pip+setuptools in). This approach works fine for me. Additionaly, focusing on pip seems to be the future path in Python packaging too. – metakermit Apr 30 '13 at 8:10
  • 1
    WORKON_HOME defaults to ~/.virtualenvs, yes. There's a line in /usr/local/bin/virtualenvwrapper.sh that sets workon_home_dir="$HOME/.virtualenvs" if [ "$workon_home_dir" = "" ]. – metakermit Apr 30 '13 at 8:12
  • Got it. Thanks. Your simple approach worked great for me on Ubuntu 12.04 when pip installing modules that are picky about using distribute (pyopencl). The trick for me was following up your pip install virtualenv virtualenv-wrapper line with pip install --upgrade distribute within the activated virtualenv that I then installed pyopencl in. I also added export PROJECT_HOME="$HOME/src" to my bashrc to enable the cool mkproject venv tool. – hobs Apr 30 '13 at 13:58

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.

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

On Ubuntu:

sudo apt-get install python-virtualenv

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

  • 1
    python-virtualenv will install both virtualenv and pip. After that just run virtualenv to create Python virtual environments. And run pip from within virtual env to install other packages. – jemeshsu Oct 31 '13 at 4:34
  • 2
    This is indeed the sanest option. the "proper" way to install things in your OS is to use your OS installer system! After that you can play with pip, preferably in a virtualenv, and never use sudofor either – MestreLion Aug 6 '14 at 19:13
  • Unfortunately, the OS provided versions of pip sometimes have significant bugs, so I often end up using the get-pip.py provided on python.org. – RichVel Dec 12 '16 at 9:15
  • @RichVel can you elaborate on the significant bugs you encountered? – danielpops Mar 23 '17 at 22:39
  • 1
    @danielpops - one example is this pip issue on Ubuntu 16.04.1, but there can be other issues with certain versions and use cases. – RichVel Mar 25 '17 at 15:29

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
  • 2
    Now deprecated in favour of pyenv. – metakermit Sep 15 '13 at 8:20
  • @kermit666 thanks. What would be the prefered way to mark my answer as outdated? Just delete it? – kioopi Sep 17 '13 at 10:16
  • 1
    well, you can either leave it as it is (there are instructions on using pyenv for people who follow the link from my comment, which are similar in concept to pythonbrew that you recommended) or better yet edit the answer with e.g. Update September 2013 by appending the new instructions. Maybe pythonbrew will become active once again in the future so I wouldn't delete your old instructions. For more info see meta. – metakermit Sep 17 '13 at 15:18
  • See my answer about pyenv, which works well. – RichVel May 7 '17 at 6:59

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.

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.

  • 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

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
    for line in f.read().splitlines():
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        if 'tar.gz<' not in line:
            continue
        for url in line.split('"'):
            if url.startswith('http'):
                url, md5 = url.split('#')
                assert md5.startswith('md5=')
                md5 = md5[4:]
                break
        else:
            continue
        break
    else:
        print('tar.gz not found')
        sys.exit(1)
    file_name = url.rsplit('/', 1)[1]
    print(file_name)
    # url = "https://pypi.python.org/packages/source/v/virtualenv/" + file_name
    os.chdir(tmp_dir)
    with open(file_name, 'wb') as fp:
        data = urlopen(url).read()
        data_md5 = hashlib.md5(data).hexdigest()
        if md5 != data_md5:
            print('md5 not correct')
            print(md5)
            print(data_md5)
            sys.exit(1)
        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.

  • The warning InsecurePlatformWarning (i.e. warning if Python is older than version 2.7.9) can be fixed by installing additional packages pyopenssl, pyasn1, ndg-httpsclient from PyPI. (It is support for SSL, decoding certificates, https via PyOpenSSL.) Without right protocols it is really not secure enough to download and run any code. – hynekcer Jun 17 '15 at 19:25
  • @hynekcer I'll give that a try. I ask myself why pip and/or request are not made dependent on those packages for appropriate (older) python versions. – Anthon Jun 17 '15 at 19:38

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

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 a 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:

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.