Linux set default python version

How to install and switch between different python versions in ubuntu 16.04.

When I work with python, sometimes I face some issues with python versions. Though I know which command will work on that case but during that parti- cular time I just forgot the exact commands and I have to search on google or stackoverflow for the exact commands.

Here I will keep the notes of installing python of different versions and chan-ging the version on per use.

How to install different versions of python?

python 2.7:

Run the following command:

Now if you run the python -V command, you will get the 2.7.12 as output. Normally installation path will be /usr/bin/python.

python 3.5:

Run the following command:

Now if you run the python -V command, you will get the 3.5.2 as output. Normally installation path will be /usr/bin/python3.5.

python 3.6:

Run the following commands:

Now if you run the python -V command, you will get the 3.6.10 as output. Normally installation path will be /usr/bin/python3.6.

python 3.7:

Run the following commands:

Now if you run the python -V command, you will get the 3.7.6 as output. Normally installation path will be /usr/bin/python3.7.

python 3.8:

Run the following commands:

Now if you run the python -V command, you will get the 3.8.1 as output. Normally installation path will be /usr/bin/python3.8.

How to switch between different python version?

If we have multiple python versions installed in our system, then python will use only one executable. Normally if we run a program called program.py by ‘python program.py’, then this program will be run by python2.7. If we check python version by ‘python -V’, it will return 2.7.12. But if we want 3.5 as the result of ‘python -V’ and the program will be run by python 3.5 executable, then we can change the default python executable in two ways.

Creating alias in bashrc:

We can create an alias within user’s home directory and add it to the bashrc. But it will only work for the current user.

Open the bashrc file by using the following command:

Add the following line to the below of the bashrc file .

Now if we use check python version using ‘python -V’, it will return 3.5.2. And if we run the program.py file using ‘python program.py’, then it will be run by python3.5 executable.

Читайте также:  Почему постоянно c windows system32 wbem wmic exe как исправить

Using update-alternatives:

To switch between python version over the all users, we can use update-alternatives command.

We will set priority of each version using update-alternatives. Python executable with the highest priority will be used as default python version.

We will set the priority by the following commands:

Here I set the priority of python 2.7, 3.5, 3.6, 3.7, 3.8 as 1, 2, 3, 4, 5. As the python3.8 has the highest priority, the default python executable is python3.8 now.

To switch between any versions, we can use the following command:

It will give a response as following:

Now default python executable can be changed by setting its corresponding selection number. For example, if we enter 4 , python will use python3.7 as default executable.

This story is just for my documentation purpose. Nothing serious 😀 😀

Источник

Изменить версию Python3 по умолчанию в Ubuntu

Я использую Ubuntu 16.04 LTS. Я python3 установил. Установлены две версии, python 3.4.3 и python 3.6 . Всякий раз, когда я использую python3 команду, она принимает python 3.4.3 по умолчанию. Я хочу использовать python 3.6 с python3 .

python3 —version шоу version 3.4.3

Я устанавливаю, ansible который поддерживает version > 3.5 . Поэтому, когда я набираю ansible в терминале, он выдает ошибку из-за python 3.4

Покажет вам ошибку:

Вам нужно обновить свою версию update-alternatives , тогда вы сможете установить версию Python по умолчанию.

Установите python3.6 по умолчанию.

Или используйте следующую команду, чтобы установить python3.6 по умолчанию:

Вы можете добиться этого, применяя следующие простые шаги —

  1. Проверьте версию Python на терминале — python —version
  2. Получите права пользователя root. По типу терминала — sudo su
  3. Запишите пароль пользователя root
  4. Выполните эту команду, чтобы перейти на Python 3.6 —
    update-alternatives —install /usr/bin/python python /usr/bin/python3 1
  5. Проверьте версию Python — python —version
  6. Готово.

Создайте символическую ссылку для / usr / bin / python3. В моем LinuxMint:

Использование этих команд может помочь вам:

  1. проверьте версию python: ls /usr/bin/python*
  2. псевдоним: alias python=’/usr/bin/pythonxx’
  3. повторного входа в систему: .

/.bashrc

  • проверьте версию Python еще раз: python —version
  • Простой ответ — добавить псевдоним для python3.6.

    Просто добавьте эту строку в файл

    / .bashrc:, alias python3=»python3.6″ затем закройте свой терминал и откройте новый. Теперь, когда вы печатаете, python3 xxx он переводится в python3.6 xxx .

    Это решение решает вашу проблему без необходимости слишком сильно настраивать вашу систему.

    РЕДАКТИРОВАТЬ :

    Как отметил Микаэль Кьер , это неверная конфигурация ANSIBLE в вашей системе.

    Установите параметр ansible_python_interpreter конфигурации в / usr / bin / python3. Параметр конфигурации ansible_python_interpreter обычно устанавливается для каждого хоста в качестве переменной инвентаризации, связанной с хостом или группой хостов:

    Как видно здесь о файле конфигурации:

    Изменения могут быть внесены и использованы в файле конфигурации, который будет обрабатываться в следующем порядке:

    Источник

    linux-notes.org

    Разработчики python не сделали поддержку версий и это не очень хорошо. Появляется ряд проблем, а именно с версиями ПО. Одни утилиты требуют версию 2.7.х, другие 3.4.х. И я хотел бы в своей статье, рассказать как можно использовать несколько версий или переключить версию python в Unix/Linux.

    Переключить версию python в Unix/Linux

    Сейчас по умолчанию, во многих Unix/Linux ОС используется питон 2.6. Чтобы проверить какая версия питона используется в системе, выполните:

    Выполним установку python:

    Так же, посмотрим:

    И так, чтобы переключить версию питона, я буду использовать несколько методов.

    -===СПОСОБ 1 — использование алиаса===-

    Один из самых простых способов — это использовать алиасы. Открываем файл:

    И, прописываем сам алиас на нужную версию питона:

    Чтобы изменения вступили в силу, выполняем:

    После этого, можно проверять версию:

    Видно что все отлично работает.

    -===СПОСОБ 2 — использование alternatives===-

    Чтобы изменить версию python глобально, я воспользуюсь alternatives утилитой:

    Если вывода не будет, — это будет означать, что python alternative еще не сконфигурирована. Чтобы это сделать, выполните ( взято в качестве примера):

    Вышеупомянутые команды будут указывать команде alternatives для создания соответствующих символических ссылок, которые будут использоваться при выполнении команды python. Я назначил python3.6 более высокий приоритет ( цифра 2), — это означает, что если не выбрана альтернатива для python, то по умолчанию будет использоваться python3.6. После выполнения вышеуказанных команд ваша версия python должна измениться на python3.6 из-за ее более высокого приоритета.

    Для переключения между вышеперечисленными версиями python теперь достаточно просто:

    Чтобы удалить питон с alternatives, используем:

    Как-то так! На этому у меня все, статья «Переключить версию python в Unix/Linux» завершена.

    Источник

    Как установить python 3.3 по умолчанию в ubuntu 13.10?

    Не надо python3 настраивать по умолчанию в системе (может через пару лет это будет и нормально работать — но не сейчас когда еще куча утилит написана на python2 и на python3 работать не будет).

    Если нужно одну программу заставить работать с python3 то отредактируйте первую строчку кода программы: Замените там
    #!/usr/bin/env python
    на
    #!/usr/bin/env python3

    Чтобы установить python 3-ей версии по умолчанию в ubuntu есть 2 способа:

    1. добавляете вот такую строчку alias python=python3 в ваш

    /.bash_aliases файл и обновляете сам файл source

    /.bashrc (этот вариант будет работать только для той учетной записи, под которой вы добавляете алиас ).

    2. выполнить sudo ln -sf python3 /usr/bin/python . эта команда обновит ссылку на питон в вашем /usr/bin каталоге (этот вариант будет работать для всех учетных записей).

    Естественно, оба варианта будут работать только если питон 3 уже установлен на машину 🙂

    Насчет sublime text 3 @brutal_lobster привел правильный конфиг. Единственное, что этот конфиг сработает, если в /usr/bin/ имеется файл python3.3. Если его там нет, путь нужно будет указать абсолютный. Например такой: «cmd»: [«/usr/bin/python3», «-u», «$file»],

    За такой совет в приличном обществе можно и по морде схлопотать.

    Большинство дистрибутивов Linux (Ubuntu — особенно) содержит кучу утилит написанных на python2 и они не будут работать на python3 с вероятностью близкой к 100%. Подменив ссылку python -> python2.7 на python -> python3 вы получите в лучшем случае сильно окривевшую систему.

    Источник

    Installing Python 3 on Linux¶

    This document describes how to install Python 3.6 or 3.8 on Ubuntu Linux machines.

    To see which version of Python 3 you have installed, open a command prompt and run

    If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:

    If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a more current Python, we recommend using the deadsnakes PPA to install Python 3.8:

    If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution’s package manager. For example on Fedora, you would use dnf :

    Note that if the version of the python3 package is not recent enough for you, there may be ways of installing more recent versions as well, depending on you distribution. For example installing the python3.9 package on Fedora 32 to get Python 3.9. If you are a Fedora user, you might want to read about multiple Python versions available in Fedora.

    Working with Python 3¶

    At this point, you may have system Python 2.7 available as well.

    This might launch the Python 2 interpreter.

    This will always launch the Python 3 interpreter.

    Setuptools & Pip¶

    The two most crucial third-party Python packages are setuptools and pip.

    Once installed, you can download, install and uninstall any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.

    Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default.

    To see if pip is installed, open a command prompt and run

    To install pip, follow the official pip installation guide — this will automatically install the latest version of setuptools.

    Note that on some Linux distributions including Ubuntu and Fedora the pip command is meant for Python 2, while the pip3 command is meant for Python 3.

    However, when using virtual environments (described below), you don’t need to care about that.

    Pipenv & Virtual Environments¶

    The next step is to install Pipenv, so you can install dependencies and manage virtual environments.

    A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

    For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.

    This page is a remixed version of another guide, which is available under the same license.

    This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.

    O’Reilly Book

    This guide is now available in tangible book form!

    All proceeds are being directly donated to the DjangoGirls organization.

    Источник

    Читайте также:  Net admin mac os
    Оцените статью