Installing Custom Python - python

I am trying to install the latest (2.7.6) version of python on my ubuntu box that already has 2.7.4 installed through the package manager. I'm up for any solution that someone has for this, but am not quite sure how to do this myself.
I have used virtualenv to create virtual python setups for different django versions, but I don't know how to use virtualenv to create an environment with an updated python version (or if it is even possible).
So to install I downloaded the source and created a custom install using the below code
wget http://python.org/ftp/python/2.7.6/Python-2.7.6.tgz
tar -xvf Python-2.7.6.tgz
cd Python-2.7.6
./configure PREFIX=$SOMEBASE/python-2.7.6
make install DESTDIR=$SOMEBASE/python-2.7.6
This seems to work for the installation, however when trying to install a package on python I get the error that it can't write to /usr/local/lib/python2.7/site-packages. I could have it write there by running as root, but wasn't sure what that would do to my existing installation and really, really don't want to break what is already there. So I would love to know if there is a way (and how) I could specify a location for the site-packages to be used (like $SOMEBASE/python-2.7.6/Lib/site-packages).

Lennart Regebro has written instructions on how to install easy_install, virtualenv, and pip for a particular Python installation.
Alternatively, there is a shell tool called virtualenvwrapper which can automate much of the process. After installing python2.7.6, (and virtualenvwrapper), you'd type
cd ~/.virtualenvs
mkvirtualenv myenv -p /path/to/python2.7.6
to make a new environment called myenv. mkvirtualenv will install easy_install and pip for you. Once you activate myenv with
workon myenv
additional modules or packages which you install with easy_install or pip will use the right version of Python and will install the modules in ~/.virtualenvs/myenv/lib/python2.7/site-packages.

Normally you rn and build Python like this:
./configure --prefix=/wherever/python-2.7.6
make
sudo make install
You'll still have to sudo when installing modules, but that's good, prevents you from doing it by mistake. They will be installed to /wherever/python-2.7.6/lib/python2.7/site-packages.

Related

Multiple python installations and pip, dude, where is my site-packages?

As we all know, Mac OS ships with its own python pre installed.
The recommendation seems to be to leave that alone and use homebrew to install a fresh python into the system.
My issue is that after installing python (and pip) using homebrew, pip is installing packages into the Mac OS site-packages instead of my own. I have confirmed I am running the "homebrew" pip:
$ which pip
/usr/local/bin/pip
But then when I pip install something I can se it is installed at:
/lib/python2.7/site-packages
Pip should be installing at /usr/local/lib/python2.7/site-packages unless i'm miss understanding something.
The surprising thing is that checking with -V yields a surprising result:
pip -V
pip 7.1.0 from /usr/local/lib/python2.7/site-packages (python 2.7)
Running pip list just after running pip install does not show the packages that were supposedly just installed by it but went to the wrong site-packages.
Adding to this, the packages installed on the /lib/python2.7/site-packages are not recognized by my $PYTHONPATH and as such I cannot use them.
To add even more confusion, I decided to use a virtualenv, but I was amazed as even using pip with the virtualenv active kept installing to the /lib/python2.7/site-packages instead of the virtualenv site-packages.
So, somehow I ended up with a homebrew pip, that installs packages outside of the homebrew site-packages and a python interpreter that cant use the packages installed by pip.
How do you recommend I go about finding the root cause and having a smooth python experience? :)
You can easily find you site-packages directory by invoking this command
python -c 'import site; print(site.getsitepackages())'
I think after you activate a virtualenv your python path should point to that environments site-package location--if not it's probably not activated. Only once you activate it will you run pip so it installs in that virtual env's site-packages. if it's not activated, it will go in whatever other site-packages it already knows about:
Step 1: create a virtual env
a la... virtualenv venv
Do this only once!
Step 2: Activate the vitual env
something like source /venv/bin/activate
Needs doing every time you want to use this virtual environment
Step 3: run pip commands, watch them get installed in the virtual env site-packages!
If you do step 3 before step 2 your not actually using the virtual environment you created, so all bets are off--That's probably the reason pip is still installing to the old location.
Now, my overall recommendation is to go further and use pyenv to install specific version of python into your /Users/username/.pyenv folder and abandon both the default OSX and homebrew packages. It's simple and you can control easily the exact version of python to use by simple issuing of command to change versions.
THEN use virtualenv in python2 or pyvenv if in python3 (not to be confused with pyenv) to build vitual environments with their own local site-packages to store pip modules. When you activate a virtualenv, your $PYTHONPATH will switch to the specific location.
The flow would then be:
Use pyenv to pull down and switch to a specific version of python you want to use--overriding homebrew and the OSX version.
Create your vitrualenv. This will create a bin that will link to the pyenv python stack you just specified in the previous step.
Activate the virtual env, and proceed.
Totally control your environment!
For one, you could try updating pip with pip install --upgrade pip command, which might or might not redirect your pip path.
Two, and I should have really started with this one is to set the preferred pip executable path in the .bash_profile or .zshrc if you are using one. The way you do it (on Mac) is by holding Shift+Command+Period to reveal hidden files, going to the User folder and opening the .bash_profile/.zshrc with a text editor. Afterward, add the path/to/bin where the pip that you require is. Like export PATH="User/Username/anaconda3/bin:$PATH" or /usr/local/bin or path/to/venv/bin. Whatever code you write in the end will overwrite the previous one.
Three, if you don't wanna change your default pip, but rather wanna use a different version for that specific case just include the full path of the pip executable like /usr/local/bin/pip list or Users/Username/Desktop/venv/bin/pip install module.

Python - No pip when creating a virtual environment

So I heard about the proper way to install packages into python by creating a new virtual environment for every project. Being on a mac (10.8) I have installed python3 using Homebrew, then I installed pip and virtualenv on this copy.
Now here comes the problem:
I create a new virtualenv, and activate it using:
virtualenv testing
source testing/bin/activate
When I type
which python
/Users/mik/Desktop/testing/bin/python
But typing
which pip
/usr/local/bin/pip
(learned of this when trying to install a package in the virtual environment, and it installed in the system wide installation in /usr/local/)
Inside the folder testing there is no file referring to pip
Extra Question: How does pip know which python to install the files to, for example pip list (which I believe refers to python 2.7) outputs the names of packages installed on python 3.3
I'll start with the last question as it explains what is happening.
The commands pip and easy_install are python scripts which are made executable on the filesystem. The python they use is the python that the first line tells to run the script. e.g. in /usr/bin/easy_install it is #!/usr/bin/python This will be Apple's python. So easy_install will install the 2.7 version of pip and virtualenv and will ignore your python3.3 setup.
The way to instal into python 3 is to install the 3.3 version of pip and virtualenv, the easiest way would be to install the Homebrew package for them. I think it is easier and less confusing to use just one package manager (Homebrew here) and not two (i.e. Homebrew and python).
You can also install easy_install directly. The way to do this is install the distribute package using python3.3 explicitly.
Python 3.4 will make this much easier as pip will always be available

How to install packages for the custom installed python? [duplicate]

Short Question
What is the proper way to install pip, virtualenv, and distribute?
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:
What is the proper way to install pip, virtualenv, and distribute?
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.
Download virtualenv:
http://pypi.python.org/pypi/virtualenv
https://pypi.python.org/packages/source/v/virtualenv/virtualenv-12.0.7.tar.gz
(or whatever is the latest version!)
Unpack the source tarball
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.
Using pip, install virtualenv into that bootstrap environment.
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.
I think Glyph means do something like this:
Create a directory ~/.local, if it doesn't already exist.
In your ~/.bashrc, ensure that ~/.local/bin is on PATH and that ~/.local is on PYTHONPATH.
Create a file ~/.pydistutils.cfg which contains
[install]
prefix=~/.local
It's a standard ConfigParser-format file.
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/
Run which easy_install to verify that it's coming from ~/.local/bin
Run pip install virtualenv
Run pip install virtualenvwrapper
Create a virtual env containing folder, say ~/.virtualenvs
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 :-)
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
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.
On Ubuntu:
sudo apt-get install python-virtualenv
The package python-pip is a dependency, so it will be installed as well.
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:
curl does ssl validation. wget doesn't.
Starting from pip 1.3.1, pip also does ssl validation.
Fewer users can upload the pypi tarball than a github tarball.
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
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:
Using pyenv and virtualenv - when selecting a Python version, it's easier to use pyenv global 3.9.1 (global to current user) or pyenv local 3.6.3 (local to current directory).
pyenv basics and use with virtualenv
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:
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.
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.
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.
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.
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
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.
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
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.

Workflow using virtualenv and pip

I have python2.6 and django1.2.3 already installed on my system (Ubuntu 10.x).
This is the setup i use for most of my projects. But for some projects I need sandboxed environments, different django version, some extra python modules and sometimes even different python version.
So, I am trying to use pip and virtualenv now,but I am unable to change python and django version. Will I have to remove default setup and move all existing projects into 1 virtualenv. Can I avoid this? Even if I do that, how can I specify a different version of python?
If I have to remove the old settings. How do i do that? I have currently most of the things installed in /usr/local/lib/python2.6/dist-packages/ but I am not sure if there is anything installed anywhere else also.
If I have a completely blank setup with just Ubuntu, what is the ideal workflow? Is it this one?
Install python
$ sudo apt-get install python-setuptools
$ sudo apt-get install python-virtualenv
$ sudo easy_install pip
$ sudo pip install virtualenvwrapper
You want to do:
virtualenv --python=/path/to/python/version --no-site-packages ENV_NAME
For example:
virtualenv --python=/usr/bin/python2.6 --no-site-packages my_project_env
If you follow this for your projects you should be able to have a separate configuration for each one.
I have installed every Python verison I need (which is 2.4, 2.5, 2.6, 2.7, 3.1 and also 3.2) from source. That's always the best thing to do, so you don't mess up the system Python.
I installed them in /opt. Like so (you need a bunch of Ubuntu packages too, first):
./configure --prefix /opt/pythonxx
make -j2; make install # j2 is a nice trick there for dualcores not everyone knows.
Then I for each version install the things I need. I start with installing Distribute:
wget http://nightly.ziade.org/distribute_setup.py
/opt/pythonxx/bin/python distribute_setup.py
(Except for Python 3, who needs distribute_setup3.py)
Then I can install pip
/opt/pythonxx/bin/easy_install pip
And virtualenv:
/opt/pythonxx/bin/pip install virtualenv
(Virtualenv3 or virtualenv5 for Python 3)
And that's it! If I want to make a virtualenv using Python 2.4, I do:
/opt/python24/bin/virtualenv foobar
And Python 2.7:
/opt/python27/bin/virtualenv foobar
Running python is just
/opt/python24/bin/python
Etc. I never install anything in the above Pythons except these modules, and PIL (because PIL is a pain, but now there is Pillow, so you don't have to do that either). I use zc.buildout and virtualenv to keep the pythons clean.
You can use virtualenv --no-site-packages ENVNAME and that will make sure the default Django in your system Python won't be included in your new environment.
For different versions of Python, you can follow these instructions from a superuser.com post.

What's the proper way to install pip, virtualenv, and distribute for Python?

Short Question
What is the proper way to install pip, virtualenv, and distribute?
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:
What is the proper way to install pip, virtualenv, and distribute?
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.
Download virtualenv:
http://pypi.python.org/pypi/virtualenv
https://pypi.python.org/packages/source/v/virtualenv/virtualenv-12.0.7.tar.gz
(or whatever is the latest version!)
Unpack the source tarball
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.
Using pip, install virtualenv into that bootstrap environment.
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.
I think Glyph means do something like this:
Create a directory ~/.local, if it doesn't already exist.
In your ~/.bashrc, ensure that ~/.local/bin is on PATH and that ~/.local is on PYTHONPATH.
Create a file ~/.pydistutils.cfg which contains
[install]
prefix=~/.local
It's a standard ConfigParser-format file.
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/
Run which easy_install to verify that it's coming from ~/.local/bin
Run pip install virtualenv
Run pip install virtualenvwrapper
Create a virtual env containing folder, say ~/.virtualenvs
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 :-)
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
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.
On Ubuntu:
sudo apt-get install python-virtualenv
The package python-pip is a dependency, so it will be installed as well.
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:
curl does ssl validation. wget doesn't.
Starting from pip 1.3.1, pip also does ssl validation.
Fewer users can upload the pypi tarball than a github tarball.
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
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:
Using pyenv and virtualenv - when selecting a Python version, it's easier to use pyenv global 3.9.1 (global to current user) or pyenv local 3.6.3 (local to current directory).
pyenv basics and use with virtualenv
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:
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.
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.
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.
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.
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
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.
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
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.

Categories

Resources