Pyenv установить версию питона

Pyenv: удобный менеджер версий python

Появлялась ли у вас хоть когда-нибудь надобность в разделении версий python на одной машине? Думаю ответ вероятнее всего будет положительным. В своей практике программирования я нередко сталкиваюсь с ситуациями, когда мне необходимо иметь под рукой сразу несколько версий Питона, да желательно ещё и самых последних. Обычно в Windows среде с этим никогда не возникает проблем, основная сложность для неподготовленного разработчика появляется при работе в unix-like операционных системах, где собственно и разворачивается большинство python-приложений (будь то веб-приложение или новомодный скрипт, автоматизирующий рутинную работу).

Сегодня я хочу кратко рассказать и показать возможности работы такого замечательного инструмента как pyenv. Данный скрипт ни что иное как удобный менеджер версий для языка программирования Python. Лучше всего сразу всё увидеть на конкретных примерах.

Установка

Pyenv можно установить либо вручную, либо используя автоматический скрипт от того же автора. Я буду использовать автоматическую установку.

$ curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash 

После этого появится сообщение о том, что необходимо добавить следующие строки кода в .profile / .bash_profile для того, чтобы автоматически обнаруживать pyenv.

export PATH="$HOME/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" 

Ах, да. Инструмент располагается в ~/.pyenv/, а все версии будущих интерпретаторов Python будут находиться ~/.pyenv/versions/.
Перед тем как устанавливать определённую версию Python, необходимо предварительно поставить зависимости:

$ sudo apt-get install build-essential $ sudo apt-get install python-dev libreadline-dev libbz2-dev libssl-dev libsqlite3-dev libxslt1-dev libxml2-dev $ sudo apt-get install git 

Для того чтобы установить определённую версию Питона необходимо выполнить следующую команду:

$ pyenv install 2.7.11 Downloading Python-2.7.11.tgz. -> https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz Installing Python-2.7.11. Installed Python-2.7.11 to /home/adylzhan/.pyenv/versions/2.7.11 

Для просмотра всех установленных версий Питона необходимо:

Читайте также:  Addoutputfilterbytype deflate application javascript

Чтобы переключиться на версию:

 $ pyenv local 2.7.11 $ python Python 2.7.11 (default, Dec 30 2015, 12:27:30) [GCC 5.2.1 20151010] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 

Создаём отдельное виртуальное окружение Питона из версии 2.7.11 и переключаемся на него:

$ pyenv virtualenv 2.7.11 django_19 Collecting virtualenv Downloading virtualenv-13.1.2-py2.py3-none-any.whl (1.7MB) 100% || 1.7MB 103kB/s Installing collected packages: virtualenv Successfully installed virtualenv-13.1.2 New python executable in /home/adylzhan/.pyenv/versions/2.7.11/envs/django_19/bin/python2.7 Also creating executable in /home/adylzhan/.pyenv/versions/2.7.11/envs/django_19/bin/python Installing setuptools, pip, wheel. done. Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in /home/adylzhan/.pyenv/versions/2.7.11/envs/django_19/lib/python2.7/site-packages Requirement already satisfied (use --upgrade to upgrade): pip in /home/adylzhan/.pyenv/versions/2.7.11/envs/django_19/lib/python2.7/site-packages adylzhan@ubuntu:~$ pyenv versions * 2.7.11 (set by /home/adylzhan/.python-version) 2.7.11/envs/django_19 django_19 $ pyenv local django_19 $ pip install django Collecting django Using cached Django-1.9-py2.py3-none-any.whl Installing collected packages: django Successfully installed django-1.9 $ python Python 2.7.11 (default, Dec 30 2015, 12:27:30) [GCC 5.2.1 20151010] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.get_version() '1.9' >>> 

Список команд pyenv можно увидеть следующим образом:

Очень удобной фичей pyenv является трекинг версий Питон для конкретных директорий через файл .python-version. Этот файл создаётся каждый раз, если выполняется команда pyenv local. Демонстрация:

$ pyenv local 2.7.11 $ mkdir demo && cd demo && echo "import django;print django.get_version()" > demo.py ~/demo$ pyenv local django_19 /demo$ python demo.py 1.9 ~/demo$ ls -la total 16 drwxrwxr-x 2 adylzhan adylzhan 4096 Dec 30 12:47 . drwxr-xr-x 6 adylzhan adylzhan 4096 Dec 30 12:46 .. -rw-rw-r-- 1 adylzhan adylzhan 41 Dec 30 12:46 demo.py -rw-rw-r-- 1 adylzhan adylzhan 10 Dec 30 12:47 .python-version /demo$ cd .. $ pyenv local 2.7.11 $ cd demo/ /demo$ cat .python-version django_19 /demo$ python demo.py 1.9 /demo$ 

Дополнительные опции для компиляции Python интерпретатора передаются через переменную окружения, например вот так:

PYTHON_CONFIGURE_OPTS="--enable-unicode=ucs4" 

Полезные ссылки

💌 Присоединяйтесь к рассылке

Понравился контент? Пожалуйста, подпишись на рассылку.

Источник

How to use pyenv to manage Python versions

As a Python developer, I install new Python versions when they come out. We get new features and performance improvements, but we don’t always want to use the latest version for everything. Some projects use older Python versions, and other projects must use a specific Python version.

If you need to install multiple Python versions, going the ol’ installer route isn’t the best idea. You end up with multiple Python executables in your PATH , such as python , python2 , python3 , python3.7 , and so on. Also it becomes really tricky to distinguish minor versions, such as python3.10.3 from python3.10.4 .

So, pyenv to the rescue! This command-line tool will handle installing and running specific Python versions!

Their README file actually explains how it works and how to install it really well. Give it a read!

As a note, for Windows I’ve often use the pyenv-win project, which has worked well for me.

To install pyenv on MacOS, I’ve just gone for Homebrew:

brew update brew install pyenv 

After installing you’ll have to add a few things to your shell, to configure it. Detailed instructions are in the README.

How I actually use pyenv

The great thing about pyenv for me is that it just works, and I only use it at the very beginning of a project, to create a virtual environment.

Once I’ve created a virtual environment using a specific Python version (which I get from pyenv ), from then on I just activate the virtual environment to get that version, and I don’t have to faff around with pyenv any more.

First, see if the version of Python you want is available (you may have to update pyenv to see recent versions, which I do with brew update && brew upgrade pyenv ):

This will show you a long output, which may contain things like the following:

. 3.10.1 3.10.2 3.10.3 3.10.4 3.10.5 3.10.6 3.10.7 3.11.0rc2 3.11-dev 3.12-dev . 

So now you know, you can install from these versions (and again, reminder to update to see the most recently-added versions).

To install a Python version:

Selecting a Python version

You can see the currently-selected Python version with this command:

And you can see all versions (including the currently selected one) with:

You can have a globally selected Python version, and then locally selected Python versions. The global version is used if no local version is selected.

You can select a local version with:

This creates a .python-version file in your current folder, which tells pyenv to use that Python version.

If you want to change the global Python version:

Using the selected Python version

Now, let’s create a virtual environment using pyenv :

pyenv exec python -m venv .venv 

This uses pyenv exec to run the python command, which will use Python 3.10.7 in our case. The -m venv .venv argument passed to python tells it to run the venv module, and gives it the name of .venv .

This will create a virtual environment in a folder called .venv .

And to be honest, this is how I use pyenv . That’s it, nothing more!

If you want to test your applications in multiple Python versions, you can also do so easily. Real Python has a great in-depth blog post that covers that, so feel free to check it out.

That’s everything! I hope you’ve found this interesting, and you’ve learned something new. If you want to delve deeper into Python and everything it has to offer, please consider joining our Complete Python Course. This mega-course covers many Python topics, and it’s currently on sale!

Thanks for reading, and I’ll see you next time.

Jose Salvatierra

Jose Salvatierra

Источник

Оцените статью