Usar diferentes versiones de Python con virtualenv
Actualmente tengo un sistema Debian corriendo con python 2.5.4. Tengo virtualenv instalado correctamente, todo está funcionando bien. ¿Existe la posibilidad de que pueda usar un virtualenv con una versión diferente de Python?
Compilé Python 2.6.2 y me gustaría usarlo con algunos virtualenv. ¿Es suficiente sobrescribir el archivo binario? ¿O tengo que cambiar algo con respecto a las bibliotecas?
19 answers
Simplemente use la opción --python
(o -p
corta) al crear su instancia virtualenv para especificar el ejecutable de Python que desea usar, por ejemplo:
virtualenv --python=/usr/bin/python2.6 <path/to/new/virtualenv/>
N.b. Para Python 3.3o posterior, refiérase a la respuesta de Aelfinn a continuación. [Nota del editor: Sé que esto normalmente debería ser un comentario, no una edición, pero un nuevo comentario estaría oculto, y acabo de pasar 45 minutos desenredando errores porque esta importante respuesta estaba enterrada bajo tres o cuatro respuestas de loro. Sólo estoy tratando de ahorrar tiempo a todos aquí.]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-16 21:12:11
Estos son pasos cuando está en un entorno de alojamiento compartido y necesita instalar y completar Python desde el código fuente y luego crear venv desde su versión de Python. Para Python 2.7.9 usted haría algo en este sentido:
mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install
Virtual env
cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p $HOME/.localpython/bin/python2.7
source ve/bin/activate
Naturalmente, esto puede ser aplicable a cualquier situación en la que desee replicar el entorno exacto en el que trabaja e implementa.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 10:25:05
ACTUALIZACIÓN: Para Python3.6, el siguiente script pyvenv
está obsoleto. En su lugar,
los documentos de Python sugieren crear el entorno virtual con el siguiente comando:
python3 -m venv <myenvname>
Para python3 (3.3+), use el método anterior o el script pyvenv
comando.
pyvenv /path/to/new/virtual/environment
Tenga en cuenta que venv
no permite crear virtualenv con otras versiones de Python. Para ello, instale y utilice el virtualenv
paquete .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 21:56:45
virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-08 23:53:53
Bajo Windows para mí esto funciona:
virtualenv --python=c:\Python25\python.exe envname
Sin el python.exe
tengo WindowsError: [Error 5] Access is denied
Tengo Python2.7. 1 instalado con virtualenv 1.6.1, y quería python 2.5.2.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-31 21:04:32
Hay una manera más fácil,
virtualenv venv --python=python2.7
Gracias a un comentario, esto solo funciona si tiene python2.7 instalado a nivel del sistema (por ejemplo, /usr/bin/python2.7).
De lo contrario, si está utilizando homebrew, puede usar la ruta para darle lo que desea.
virtualenv venv --python=/usr/local/bin/python
Puede encontrar la ruta a su instalación de python con
which python
Esto también funcionará con python 3.
which python3
>> /usr/local/bin/python3
virtualenv venv --python=/usr/local/bin/python3
Finalmente condensando a:
virtualenv venv -p `which python`
virtualenv venv -p `which python3`
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-24 07:28:36
Mac OSX 10.6.8 (Snow Leopard):
1) Cuando haces pip install virtualenv
, el comando pip se asocia con una de tus versiones de python, y virtualenv
se instala en esa versión de python. Usted puede hacer
$ which pip
Para ver qué versión de python es. Si ves algo como:
$ which pip
/usr/local/bin/pip
Entonces haz:
$ ls -al /usr/local/bin/pip
lrwxrwxr-x 1 root admin 65 Apr 10 2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip
Puede ver la versión de python en la salida.
De forma predeterminada, esa será la versión de python que se usa para cualquier entorno nuevo que cree. Sin embargo, puede especificar cualquier versión de python instalada en su computadora para usarla dentro de un nuevo entorno con el -p flag
:
$ virtualenv -p python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3.2
New python executable in my_env/bin/python
Installing setuptools, pip...done.
virtualenv my_env
creará una carpeta en el directorio actual que contendrá los archivos ejecutables de Python, y una copia del pip [comando] que puede usar para instalar otros paquetes.
Http://docs.python-guide.org/en/latest/dev/virtualenvs /
virtualenv
simplemente copia python desde una ubicación en su computadora en el directorio my_env/bin / recién creado.
2) El sistema python está en /usr/bin
, mientras que las diversas versiones de python que instalé estaban, por defecto, instaladas en:
/usr/local/bin
3) Las varias pitones que instalé tienen nombres como python2.7
o python3.2
, y puedo usar esos nombres en lugar de rutas completas.
========VIRTUALENVWRAPPER=========
1) Tuve algunos problemas para que virtualenvwrapper funcionara. Esto es lo que terminé poniendo en ~/.bash_profile
:
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects #Not very important -- mkproject command uses this
#Added the following based on:
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
2) El -p option
funciona de manera diferente con virtualenvwrapper: Tengo que especificar la ruta completa al intérprete de python que se utilizará en el nuevo entorno (cuando no quiero usar la versión predeterminada de python):
$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate
removes the 'bin' directory of the environment activated with 'source
activate' from PATH.
A diferencia de virtualenv, virtualenvwrapper creará el entorno en la ubicación especificada por la variable de entorno WORK WORKON_HOME. Eso mantiene todos sus entornos en un solo lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 02:49:52
Supongamos que actualmente tiene instalado python 2.7 en su virtualenv. Pero si quieres hacer uso de python3.2
, tendrás que actualizar esto con:
$ virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv
Luego activa tu virtualenv por:
$ source activate name_of_your_virtualenv
Y luego haga: python --version
en el shell para comprobar si su versión está actualizada.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-08 18:29:34
Puede llamar a virtualenv
con la versión de python que desee. Por ejemplo:
python3 -m virtualenv venv
O alternativamente apunta directamente a tu ruta virtualenv. por ejemplo, para windows:
c:\Python34\Scripts\virtualenv.exe venv
Y ejecutando:
venv/bin/python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Puede ver la versión de python instalada en el entorno virtual
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-19 13:03:03
El enfoque -p
funciona bien, pero tienes que recordar usarlo cada vez. Si su objetivo es cambiar a una versión más reciente de Python en general, eso es un dolor y también puede conducir a errores.
Su otra opción es establecer una variable de entorno que haga lo mismo que -p
. Establezca esto a través de su archivo ~/.bashrc
o donde administre variables de entorno para sus sesiones de inicio de sesión:
export VIRTUALENV_PYTHON=/path/to/desired/version
Entonces virtualenv
usará eso cada vez que no especifique -p
en el comando alinear.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-05 20:57:44
En el mac uso pyenv y virtualenvwrapper. Tuve que crear un nuevo virtualenv. Necesitas homebrew que asumo que has instalado si estás en un mac, pero solo por diversión:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install pyenv
pyenv install 2.7.10
pyenv global 2.7.10
export PATH=/Users/{USERNAME}/.pyenv/versions/2.7.10/bin:$PATH
mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python {virtual_env_name}
También congelé mis requisitos primero para poder simplemente reinstalar en el nuevo virtualenv con:
pip install -r requirements.txt
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 21:03:08
Aún más fácil, mediante el uso de sustitución de comandos para encontrar python2 para usted:
virtualenv -p $(which python2) <path/to/new/virtualenv/>
O cuando se utiliza virtualenvwrapper :
mkvirtualenv -p $(which python2) <env_name>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-19 13:28:50
En el subsistema de windows para linux:
-
Crear un entorno para python3:
virtualenv --python=/usr/bin/python3 env
-
Actívalo:
source env/bin/activate
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-26 11:45:41
Estos dos comandos deberían funcionar bien para un novato
virtualenv -p python2 myenv
(Para python2)
virtualenv -p python3 myenv
(Para python3)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 10:03:25
Para Mac(High Sierra), instale el virtualenv en python3 y cree un virtualenv para python2:
$ python3 -m virtualenv --python=python2 vp27
$ source vp27/bin/activate
(vp27)$ python --version
Python 2.7.14
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-24 00:30:05
Me funcionó
sudo apt-get install python3-minimal
virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 06:53:41
Sí, las respuestas anteriores es correcta y funciona correctamente en los sistemas basados en Unix como Linux & MAC OS X.
Traté de crear virtualenv para Python2 & Python3 con los siguientes comandos.
Aquí he utilizado venv2 & venv3 como sus nombres para Python2 & Python3, respectivamente.
Python2 "
MacBook-Pro-2:~ admin$ virtualenv venv2 --python=`which python2`
Running virtualenv with interpreter /usr/local/bin/python2
New python executable in /Users/admin/venv2/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$
MacBook-Pro-2:~ admin$ ls venv2/bin/
activate easy_install pip2.7 python2.7
activate.csh easy_install-2.7 python wheel
activate.fish pip python-config
activate_this.py pip2 python2
MacBook-Pro-2:~ admin$
Python3 "
MacBook-Pro-2:~ admin$ virtualenv venv3 --python=`which python3`
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/admin/venv3/bin/python3
Also creating executable in /Users/admin/venv3/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$
MacBook-Pro-2:~ admin$ ls venv3/bin/
activate easy_install pip3.6 python3.6
activate.csh easy_install-3.6 python wheel
activate.fish pip python-config
activate_this.py pip3 python3
MacBook-Pro-2:~ admin$
Comprobación de ubicaciones de instalación de Python
MacBook-Pro-2:~ admin$ which python2
/usr/local/bin/python2
MacBook-Pro-2:~ admin$
MacBook-Pro-2:~ admin$ which python3
/usr/local/bin/python3
MacBook-Pro-2:~ admin$
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-30 07:42:05
En windows:
py -3.4x32 -m venv venv34
O
py -2.6.2 -m venv venv26
Esto utiliza el py
launcher que encontrará el ejecutable de python adecuado para usted (suponiendo que lo tenga instalado).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 23:22:22
virtualenv -p python3 myenv
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-03 08:51:50