250

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:

Community
  • 1
  • 1
Matthew Rankin
  • 457,139
  • 39
  • 126
  • 163
  • 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 https://python-guide.readthedocs.org/en/latest/starting/install/linux.html), and if so, why? – Amelio Vazquez-Reina Apr 18 '13 at 21:26
  • As of June 2013, [this answer](http://stackoverflow.com/a/14753678/148680) seems to be the most comprehensive with regard to which packaging library should be used with virtualenv. – chb Jun 17 '13 at 03:32
  • [It has become much easier with Python 3.4](http://stackoverflow.com/a/21456786/974555). – gerrit Jan 30 '14 at 12:47
  • 2
    What's wrong with `sudo apt-get install python-{pip,virtualenv}`??? – MestreLion Aug 06 '14 at 19:17
  • @MestreLion installing from a package mirror may give you outdated versions and/or pip and virtualenv versions that do not match your python interpreter of choice. –  Feb 28 '15 at 03:12
  • @tristan: Outdated, perhaps. But guaranteed to be fully *compatible* with your system, *supported* by your distro, and get *automatically* all *security* patches. – MestreLion Feb 28 '15 at 07:43
  • As for "do not match your python interpreter"... there's `python3-pip` and `python3-virtualenv` for most distros. – MestreLion Feb 28 '15 at 07:46
  • @tristan I love pip and virtualenv, they are amazing for installing libraries that are either not provided by your distro or too outdated. But for installing pip and virtualenv *themselves* I see no reason not to use your system's repositories. – MestreLion Feb 28 '15 at 07:50
  • 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. –  Mar 02 '15 at 16:24
  • 2
    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 05 '16 at 18:47
  • 1
    `http://python-distribute.org/distribute_setup.py` redirects to 404 :( – jitter May 01 '17 at 23:29
  • 1
    This question is very outdated, along with the answers. `pip` has come pre-installed with Python since 3.4 (and 2.7.9); virtualenv since 3.3; and `distribute` has been obsolete for a long time (per PyPA recommendations, use `build` and `twine`, which you can trivially install using `pip`; or use any number of third-party options such as `poetry`; even the most bare-bones approach would use `setuptools` rather than `distribute`). – Karl Knechtel Oct 03 '21 at 18:49

15 Answers15

173

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.

Walker Hale IV
  • 3,252
  • 2
  • 21
  • 11
  • 13
    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 - http://stackoverflow.com/questions/6812207/how-can-i-correctly-install-multiple-non-package-distribute-virtualenv-pip-ecosys - works perfectly. – lofidevops 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 09 '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 04:07
  • 1
    Where do you install `virtualenvwrapper`? [The docs](http://virtualenvwrapper.readthedocs.org/en/latest/install.html#basic-installation) warn specifically not to install it in a virtualenv (though [it seems to work](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/198/)). – Aryeh Leib Taurog Jul 24 '13 at 19:32
  • 1
    distribute has since been merged back to setuptools, so it's best to not think of distribute at all anymore :) – bukzor Dec 20 '13 at 02:10
  • Don't ever remove your INITIAL_ENV, otherwise you will be in a lot of trouble. – fast tooth Jun 26 '14 at 15:14
  • And requires the Internet. I installed Python2.7.9 from source on a box with no Internet, downloaded venv, used the python setup.py install which installed venv fine, but when I tried to create a venv it couldn't find pip and failed. – volvox Jan 07 '15 at 15:04
  • I made it into a slightly more polished installer script here: https://github.com/altaurog/venvinstaller – Aryeh Leib Taurog Jun 06 '17 at 20:08
  • 1
    I think this answer is out-of-date. Newer versions of virtualenv don't include `virtualenv.py` – JamesTheAwesomeDude Apr 28 '20 at 19:32
21

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

metakermit
  • 21,267
  • 15
  • 86
  • 95
Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • @Vinay — Thanks for the info. Maybe I should have mentioned that I'm only doing this for versions of Python that I install—MacPython 2.7, MacPython2.6. The OS X installed version of Python 2.5, I leave alone and don't pollute its global-site directory. – Matthew Rankin Dec 01 '10 at 14:34
  • 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 04 '11 at 10:20
  • @Tartley: I used the same name that Glyph used. I also said "something like", meaning that the OP is free to choose their own name. – Vinay Sajip Mar 04 '11 at 14:08
  • @Vinay, Right, understood. I didn't mean to sound critical, sorry if it came across that way. I was attempting to clarify my understanding about what a good name would be. Thanks. – Jonathan Hartley Mar 04 '11 at 15:26
  • On Ubuntu 10.10, I install Python3.2 from source, then follow the above. While running distribute_setup.py, it fails while trying to install setuptools, with the following message {{{ Checking .pth file support in /home/jhartley/.python32/lib/python3.2/site-packages/ /usr/local/bin/python3.2 -E -c pass TEST FAILED: /home/jhartley/.python32/lib/python3.2/site-packages/ does NOT support .pth files error: bad install directory or PYTHONPATH... ...and your PYTHONPATH env var currently contains: '/home/jhartley/.python32:' }}} – Jonathan Hartley Mar 09 '11 at 19:13
  • Sorry for the terseness - I was trying to fit a meaningful description of my problem into one comment. Any clues anyone has as to what I'm doing wrong would be much appreciated, thanks! – Jonathan Hartley Mar 09 '11 at 19:21
  • 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
  • Same problem here, but for me, I had to add ~/.local/lib/python2.7/site-packages to the PYTHONPATH (Ubuntu 11.04) – Dan May 11 '11 at 17:14
  • The instructions don't work for me because you do not recommend a way to install pip, and so I can't complete step #6 – Dan May 11 '11 at 17:17
  • 1
    One last problem with this approach: virtualenv is incompatible with using the .pydistutils.cfg file. See https://github.com/pypa/virtualenv/issues/88/ – Dan 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 08:09
  • @DiggyF: Nowadays, virtualenv comes with pip and pip is installed automatically when you create a new virtual environment. – Vinay Sajip Jun 27 '11 at 13:36
  • @Vinay Sajip, shouldn't it then be: `easy_install virtualenv` in step 6? On my system pip was not available yet before step 6. – SiggyF Jun 27 '11 at 16:40
  • 1
    @DiggyF: Some people (like me) had installed pip before virtualenv. Of course, if you hadn't, then you would do easy_install, which would be available after step 4. Both pip and Distribute make use of setuptools functionality - Distribute is a fork of setuptools and so provides it directly, whereas pip does not include setuptools and needs either setuptools or Distribute installed first. – Vinay Sajip Jun 27 '11 at 17:35
  • 5
    The ~/.local thing comes from PEP 370. – merwok Jun 30 '11 at 14:51
17

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
Community
  • 1
  • 1
metakermit
  • 21,267
  • 15
  • 86
  • 95
  • 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](http://packages.ubuntu.com/quantal/python-pip) 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](http://guide.python-distribute.org/future.html) in Python packaging too. – metakermit Apr 30 '13 at 08: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 08: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
15

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.

gerrit
  • 24,025
  • 17
  • 97
  • 170
  • the "preceded call" would be `python -m venv venv` which would create the dir `venv` where the virtual env resides. To activate this venv call `source venv/bin/activate`. – Risadinha Jul 16 '21 at 10:12
10

On Ubuntu:

sudo apt-get install python-virtualenv

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

Jeff Widman
  • 22,014
  • 12
  • 72
  • 88
Arik Halperin
  • 458
  • 4
  • 8
  • 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 04: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 `sudo`for either – MestreLion Aug 06 '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 09: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](https://github.com/pypa/pip/issues/3862) on Ubuntu 16.04.1, but there can be other issues with certain versions and use cases. – RichVel Mar 25 '17 at 15:29
  • I've had other problems with OS-provided Python versions, e.g. Ubuntu 14.04 has Python 2.7.9 which requires considerable effort to get it upgraded with right SSL modules so it handles SNI (server name indication) as client, using an Ansible script that still ended up failing on a new server. My new approach is to use [pyenv](https://github.com/pyenv/pyenv) which installs a new Python version and supports virtualenvs - included in Python 3.3+, easily installed in Python 2.7, and works very well to insulate the "new Python" setup from system Python. – RichVel May 07 '17 at 06:28
  • I expanded my comment about `pyenv` into a [full answer](http://stackoverflow.com/a/43828665/992887) – RichVel May 07 '17 at 06:58
6

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.
bukzor
  • 37,539
  • 11
  • 77
  • 111
5

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
vk1011
  • 7,011
  • 6
  • 26
  • 42
kioopi
  • 2,170
  • 2
  • 18
  • 26
  • @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](http://meta.stackexchange.com/questions/11705/how-to-deal-with-obsolete-answers). – metakermit Sep 17 '13 at 15:18
  • See my [answer](http://stackoverflow.com/a/43828665/992887) about `pyenv`, which works well. – RichVel May 07 '17 at 06:59
4

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.

Older distributions - SSL module problems

One reason to use pyenv was that there were often problems with upgrading Python SSL modules when using older system-provided Python versions. This may be less of a problem now that current Linux distributions support Python 3.x.

RichVel
  • 7,030
  • 6
  • 32
  • 48
3

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.

Alexis Métaireau
  • 10,767
  • 5
  • 24
  • 34
  • 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
3

Install ActivePython. It includes pip, virtualenv and Distribute.

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
2
  • 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.

Anthon
  • 69,918
  • 32
  • 186
  • 246
  • 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
2

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
maoyang
  • 1,067
  • 1
  • 11
  • 11
  • This is the simplest and most up-to-date answer. I've just done this before moving a legacy Python 2.7 easy_install project over to Python 3.8 and pip. – Dave Everitt Oct 06 '20 at 17:49
2

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.

merwok
  • 6,779
  • 1
  • 28
  • 42
  • [you could install distribute/pip/virtualenv all three at once in a much simpler way](http://stackoverflow.com/a/12946537/4279) – jfs Nov 25 '12 at 19:30
0

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

Victor S
  • 5,098
  • 5
  • 44
  • 62
0

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.

Community
  • 1
  • 1
suhailvs
  • 20,182
  • 14
  • 100
  • 98