2011-07-25 12 views
8

Estoy desarrollando aplicaciones de Python en Ubuntu. Quiero configurar un Distribute/virtualenv/pip ecosystem para administrar mis paquetes de Python independientemente de cualquier paquete Python del sistema (que administro en Synaptic, o mejor dicho, dejo que el sistema los administre).¿Cómo puedo instalar correctamente múltiples ecosistemas Distribute/virtualenv/pip sin paquete en Ubuntu?

Pude simplemente instalar los paquetes del sistema python-setuptools, python-virtualenv y python-pip y estar de mi manera feliz, pero también quiero poder obtener las versiones más recientes/específicas de Distribute, virtualenv y pip. No hay PPA para estos, así que tendré que instalarlos manualmente.

Una última complicación, es que quiero poder hacer esto para múltiples versiones de Python. Es decir, configure un ecosistema para python2.6, otro para python, otro para python3, o en un sistema de 64 bits otro para chrooted 32-bit Python.

supongo que el proceso sería algo así como:

  • utilizar Python X instalar mi propia copia de distribuir a un lugar en mi carpeta de inicio
  • Usando indie Distribuir, easy_install pip
  • El uso de PIP indie, instale virtualenv
  • usando virtualenv independiente, crear entorno virtual
  • Activa entorno virtual, instalar paquetes
  • Repita para Python Y, Z y Q

¿Qué opciones de instalación/configuración estoy buscando?

+0

esto parece una solución simple http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/5177027#5177027 – d3vid

+0

actualmente investigar una alternativa con virtualenvwrapper ver https://bitbucket.org/dhellmann/virtualenvwrapper/issue/105 y https://bitbucket.org/dhellmann/virtualenvwrapper/issue/106 – d3vid

Respuesta

0

Abundando en JF Sebastián y contribuciones de nealmcb, en estos días hago uso de mi sistema de hecho la versión empaquetada de virtualenvwrapper (disponible en Ubuntu 12.04 y posteriores).

virtualenvwrapper es un conjunto de extensiones de la herramienta virtualenv de Ian Bicking. Las extensiones incluyen envoltorios para crear y eliminar entornos virtuales y, de lo contrario, administrar el flujo de trabajo de desarrollo, lo que facilita el trabajo en más de un proyecto a la vez sin introducir conflictos en sus dependencias.

Las características clave que utilizo (en respuesta a esta pregunta) son:

  • mkvirtualenv --python=PYTHON_EXE crea un virtualenv utilizando un archivo ejecutable de Python específica (no tiene que ser una versión empaquetada sistema)
  • allvirtualenv pip install -U pip actualizaciones pip en todas virtualenvs

El AMBIENTAL t Las variables que JFS mencionó son de hecho útiles para manipular: PIP_DOWNLOAD_CACHE, VIRTUALENV_USE_DISTRIBUTE, WORKON_HOME, VIRTUALENVWRAPPER_PYTHON.

El único motivo para actualizar virtualenv es obtener la última versión de setuptools (anteriormente conocida como Distribuir, anteriormente conocida como setuptools). No he tenido la necesidad de hacer esto todavía, pero sospecho que sería más fácil comenzar con un nuevo virtualenv y actualizar Distribute/setuptools primero, luego actualizar pip, luego instalar otras bibliotecas.

Si una versión nueva de virtualenv es estrictamente necesaria, una modificación de the bootstrap script debería hacer.

7

Basado en Walker Hale IV's answer a una similar (pero distinto;)) pregunta, hay dos claves para hacer esto:

  • que no necesita instalar distribuir y pip porque éstos se incluyen automáticamente en una nuevo entorno virtual (y, presumiblemente, sólo quieren las versiones que han sido probados con virtualenv)
  • que pueden utilizar el código fuente virtualenv para crear un nuevo entorno virtual, en lugar de utilizar la versión instalada del sistema de virtualenv

De modo que el flujo de trabajo es:

  • instalar Python versión X en su sistema
  • descarga versión de código fuente virtualenv Q (probablemente la última)
  • crear nuevo entorno virtual con Python X y Q virtualenv
  • su nuevo VE ahora ejecuta Python X y las últimas versiones estables de pip y distribuye
  • pip instala cualquier otro paquete
  • easy_install cualquier otro paquete que no puedas instalar

Notas:

  • En su nuevo entorno virtual, se puede instalar nuevos (o viejos) versiones de distribuir, PIP o virtualenv.(Creo)
  • No utilizo la técnica de WH4 de crear un entorno virtual de bootstrap. En cambio, creo el nuevo entorno virtual a partir de la fuente virtualenv cada vez.
  • Esta técnica debe poder usarse en cualquier sistema operativo.
  • Si estuviera explicando esto a alguien nuevo en todo el concepto del ecosistema Distribute/pip/virtualenv, lo explicaría de una manera virtualenv-céntrica.

He escrito un script bash que hace los conceptos básicos en Ubuntu:


#! /bin/bash 
# Script to create a python virtual environment 
# independently of the system version of virtualenv 
# 
# Ideally this would be a cross-platform Python 
# script with more validation and fewer TODOs, 
# but you know how it is. 

# = PARAMETERS = 
# $1 is the python executable to use 
# examples: python, python2.6, /path/to/python 
# $2 is the new environment folder 
# example: /path/to/env_folder/name 
## TODO: should be just a name 
## but I can't concatenate strings in bash 
# $3 is a pip requirements file 
# example: /path/to/req_folder/name.txt 
# you must uncomment the relevant code below to use $3 
## TODO: should be just a name 
## but I can't concatenate strings in bash 

# other parameters are hard-coded below 
# and you must change them before first use 

# = EXAMPLES OF USE = 
# . env_create python2.5 /home/env/legacy 
## creates environment "legacy" using python 2.5 
# . env_create python /home/env/default 
## creates environment "default" using whatever version of python is installed 
# . env_create python3.2 /home/env/bleeding /home/req/testing.txt 
## creates environment "bleeding" using python 3.2 and installs packages from testing.txt using pip 

# = SET UP VARIABLES = 
# Required version of virtualenv package 
VERSION=1.6.4 
# Folder to store your virtual environments 
VE_FOLDER='/media/work/environments' 
## TODO: not used because I can't concatenate strings in bash 
# Folder to store bootstrap (source) versions of virtualenv 
BOOTSTRAP_FOLDER='/media/work/environments/bootstrap' 
## TODO: not used because I can't concatenate strings in bash 
# Folder to store pip requirements files 
REQUIREMENTS_FOLDER='/media/work/environments/requirements' 
## TODO: not used because I can't concatenate strings in bash 
# Base URL for downloading virtualenv source 
URL_BASE=http://pypi.python.org/packages/source/v/virtualenv 
# Universal environment options 
ENV_OPTS='--no-site-packages --distribute' 
# $1 is the python interpreter 
PYTHON=$1 
# $2 is the target folder of the new virtual environment 
VE_TARGET=$2 
# $3 is the pip requirements file 
REQ_TARGET=$3 

## = DOWNLOAD VIRTUALENV SOURCE = 
## I work offline so I already have this downloaded 
## and I leave this bit commented out 
# cd $BOOTSTRAP_DIR 
# curl -O $URL_BASE/virtualenv-$VERSION.tar.gz 
## or use wget 

# = CREATE NEW ENV USING VIRTUALENV SOURCE = 
cd $BOOTSTRAP_FOLDER 
tar xzf virtualenv-$VERSION.tar.gz 
# Create the environment 
$PYTHON virtualenv-$VERSION/virtualenv.py $ENV_OPTS $VE_TARGET 
# Don't need extracted version anymore 
rm -rf virtualenv-$VERSION 
# Activate new environment 
cd $VE_TARGET 
. bin/activate 

# = INSTALL A PIP REQUIREMENTS FILE = 
## uncomment this if you want to automatically install a file 
# pip install -r $REQ_TARGET 

# = REPORT ON THE NEW ENVIRONMENT = 
python --version 
pip freeze 
# deactivate 
## uncomment this if you don't want to start in your environment immediately 

de salida es como la siguiente (con la descarga de apagado y encendido de desactivación):

 
[email protected]:/home/user$ . env_create python3 /media/work/environments/test 
New python executable in /media/work/environments/test/bin/python3 
Also creating executable in /media/work/environments/test/bin/python 
Installing distribute...............done. 
Installing pip...............done. 
Python 3.2 
distribute==0.6.19 
wsgiref==0.1.2 
[email protected]:/media/work/environments/test$ 
+1

Funciona bien en Mac OSX Lion con la siguiente corrección de errores: BOOTSTRAP_DIR debe ser BOOTSTRAP_FOLDER. – ohmi

+2

[virtualenvwrapper] (http://virtualenvwrapper.readthedocs.org/en/latest/) simplifica la administración de múltiples entornos virtuales, por ejemplo, los comandos 'workon',' mkvirtualenv'/'rmvirtualenv'. También encuentro útiles las variables de entorno 'PIP_DOWNLOAD_CACHE',' VIRTUALENV_USE_DISTRIBUTE', 'WORKON_HOME',' VIRTUALENVWRAPPER_PYTHON'. – jfs

+0

con respecto a la concatenación de cadenas en bash, puede: foo = 'abc'; bar = 'def'; baz = $ {foo} $ {bar} –

0

Como señaló @jfsebastian, virtualenvwrapper hace todo o parte de lo que está pidiendo.

http://virtualenvwrapper.readthedocs.org/

virtualenvwrapper es un conjunto de extensiones para la herramienta de Ian Bicking virtualenv . Las extensiones incluyen envoltorios para crear y eliminar entornos virtuales y administrar el flujo de trabajo de desarrollo, , lo que facilita el trabajo en más de un proyecto a la vez sin introducir conflictos en sus dependencias.

Cuestiones relacionadas