Ubuntu выбрать версию python

Change the Python3 default version in Ubuntu

I am using Ubuntu 16.04 LTS . I have python3 installed. There are two versions installed, python 3.4.3 and python 3.6 . Whenever I use python3 command, it takes python 3.4.3 by default. I want to use python 3.6 with python3 . python3 —version shows version 3.4.3 I am installing ansible which supports version > 3.5 . So, whenever, I type ansible in the terminal, it throws error because of python 3.4

sudo update-alternatives --config python3 update-alternatives: error: no alternatives for python3 

@Mikael Different Python versions are not alternatives on Ubuntu. The OS relies on a specific version (or versions) being installed.

10 Answers 10

sudo update-alternatives --config python 
update-alternatives: error: no alternatives for python3 

You need to update your update-alternatives , then you will be able to set your default python version.

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.4 1 sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2 
sudo update-alternatives --config python 

Or use the following command to set python3.6 as default:

sudo update-alternatives --set python /usr/bin/python3.6 

This answer will probably break apt . After selecting a different version of python try to run sudo apt update . If it gives you an error like ModuleNotFoundError: No module named ‘apt_pkg’ you want to go to /usr/lib/python3/dist-packages and create the symlink: ln -s apt_pkg.cpython-<34m,36m>-x86_64-linux-gnu.so .

Don’t do this. It will break apt like @Giacomo mentioned along with other OS components like do-release-upgrade . Simply use an alias instead.

Читайте также:  Php include get запрос

Works fine in Ubuntu 18.04 LTS without breaking APT. Note to those confused: if you are getting the error: no alternatives for python message, then you need to run the —install commands following first (replacing the python versions you want to use as appropriate, and the numbers at the end are just for order) then you run the —config command again and you will be asked which version you want to use by default.

You can achieve this by applying below simple steps —

  1. Check python version on terminal: python —version
  2. Execute this command to switch to python 3.6:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1 

if you have multiple version of python in your system. You just need to update the symbolic link of python inside /usr/bin/

root@irshad:/usr/bin# ls -lrth python* lrwxrwxrwx 1 root root 9 Apr 16 2018 python -> python2.7 -rwxr-xr-x 1 root root 3.6M Nov 12 2018 python2.7 -rwxr-xr-x 2 root root 4.4M May 7 14:58 python3.6 

In above example if you see the output of python —version you will get python2.7

Now update the python symlink using below command-

root@irshad:/usr/bin# unlink python root@irshad:/usr/bin# ln -s /usr/bin/python3.6 python root@irshad:/usr/bin# python --version Python 3.6.8 

I agree this answer is the best. However, I would add that some people’s newly installed python won’t be located in /usr/bin/pythonX.X . Instead figure out the location with which pythonX.X and substitute in.

I couldn’t find the newly installed python3.9 in /user/bin/, any suggestion please? I am on Ubuntu 18.04

I needed this variation: sudo unlink /usr/bin/python3, sudo ln -s /usr/bin/python3.8 /usr/bin/python3, python3 —version

Using these commands can help you:

  1. check the version of python: ls /usr/bin/python*
  2. alias: alias python=’/usr/bin/pythonxx’ (add this to . ~/.bashrc )
  3. re-login or source . ~/.bashrc
  4. check the python version again: python —version

First check that you have a python3.6 folder?

If you have «python3.6» folder, you are good to go. Now update-alternatives

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1 

then update new config for python3

sudo update-alternatives --config python3 

Finally, check default python3 version:

Create symlink for /usr/bin/python3. In my LinuxMint:

# ls -lh /usr/bin/python3 /usr/bin/python lrwxrwxrwx 1 root root 9 ноя 24 2017 /usr/bin/python -> python2.7 lrwxrwxrwx 1 root root 9 сен 6 2017 /usr/bin/python3 -> python3.5 # mv /usr/bin/python /usr/bin/python.bak # cp /usr/bin/python3 /usr/bin/python # python --version Python 3.5.2 

An easy answer would be to add an alias for python3.6.

Just add this line in the file ~/.bashrc : alias python3=»python3.6″ , then close your terminal and open a new one. Now when you type python3 xxx it gets translated to python3.6 xxx .

This solution fixes your problem without needing to tweak your system too heavily.

As Mikael Kjær pointed out, this is a misconfiguration of ansible with your system.

Set the ansible_python_interpreter configuration option to /usr/bin/python3. The ansible_python_interpreter configuration option is usually set per-host as an inventory variable associated with a host or group of hosts:

 # Example inventory that makes an alias for localhost that uses python3 [py3-hosts] localhost-py3 ansible_host=localhost ansible_connection=local [py3-hosts:vars] ansible_python_interpreter=/usr/bin/python3 

As seen here about the config file :

Changes can be made and used in a configuration file which will be processed in the following order:

* ANSIBLE_CONFIG (an environment variable) * ansible.cfg (in the current directory) * .ansible.cfg (in the home directory) * /etc/ansible/ansible.cfg 

Источник

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

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

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

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

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

lrwxrwxrwx. 1 root root 7 Apr 11 10:38 /usr/local/bin/python -> python2 lrwxrwxrwx. 1 root root 9 Apr 11 10:38 /usr/local/bin/python2 -> python2.7 -rwxr-xr-x. 1 root root 6294753 Apr 11 10:37 /usr/local/bin/python2.7 -rwxr-xr-x. 1 root root 1687 Apr 11 10:38 /usr/local/bin/python2.7-config lrwxrwxrwx. 1 root root 16 Apr 11 10:38 /usr/local/bin/python2-config -> python2.7-config lrwxrwxrwx. 1 root root 9 Apr 11 11:10 /usr/local/bin/python3 -> python3.6 -rwxr-xr-x. 2 root root 9961651 Apr 11 11:08 /usr/local/bin/python3.6 lrwxrwxrwx. 1 root root 17 Apr 11 11:10 /usr/local/bin/python3.6-config -> python3.6m-config -rwxr-xr-x. 2 root root 9961651 Apr 11 11:08 /usr/local/bin/python3.6m -rwxr-xr-x. 1 root root 3083 Apr 11 11:10 /usr/local/bin/python3.6m-config lrwxrwxrwx. 1 root root 16 Apr 11 11:10 /usr/local/bin/python3-config -> python3.6-config lrwxrwxrwx. 1 root root 14 Apr 11 10:38 /usr/local/bin/python-config -> python2-config

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

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

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

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

alias python='/usr/local/bin/python3.6'

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

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

$ python --version Python 3.6.1

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

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

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

# alternatives --list | grep -i python

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

# alternatives --install /usr/bin/python python /usr/local/bin/python3.6 2 # alternatives --install /usr/bin/python python /usr/local/bin/python2.7 1

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

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

# alternatives --config python

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

# update-alternatives --remove python /usr/local/bin/python3.6

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

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Рубрики

  • Arch Linux (167)
  • Commands (36)
  • Debian’s (635)
    • Administration tools Ubuntu (37)
    • Backups Debian’s (7)
    • Database в Ubuntu (58)
    • Games (игры) (1)
    • Monitoring в Debian и Ubuntu (49)
    • Virtualization в Ubuntu / Debian/ Linux Mint (41)
      • Docker (22)
      • Kubernetes (6)
      • KVM (4)
      • OpenVZ (3)
      • Vagrant (5)
      • VirtualBox (6)
      • ArgoCD (1)
      • Concourse (1)
      • Gitlab (1)
      • Jenkinks (4)
      • Spinnaker (1)
      • Apache (32)
      • Cherokee (1)
      • FTP-services (5)
      • Lighttpd (1)
      • Nginx (26)
      • PHP (27)
      • Proxy для Debian’s (2)
      • Tomcat (4)
      • Панели управления в Ubuntu/Debian/Mint (24)
      • Установка и настройка почты на Ubuntu/Debian (12)
      • Хранилища (clouds) (2)
      • Administration tools freeBSD (19)
      • Database во FreeBSD (52)
      • Monitoring во freeBSD (37)
      • Virtualization во FreeBSD (22)
      • VoIP (1)
      • Установка Web сервисов (91)
      • Установка и настройка почты (6)
      • Установка из ports (пакетов) (19)
      • Установка из sorce code (исходников) (23)
      • Непрерывная интеграция (CI) (27)
      • Database в MacOS (36)
      • Monitoring в Mac OS (31)
      • Security (безопасность) (12)
      • Virtualization в Mac OS (30)
        • Docker (19)
        • Kubernetes (6)
        • Vagrant (5)
        • VirtualBox (5)
        • ArgoCD (1)
        • CircleCI (1)
        • Concourse (1)
        • Gitlab (1)
        • Jenkinks (4)
        • Spinnaker (1)
        • Administration tools CentOS (49)
        • Backups RPM’s (4)
        • Database в CentOS (68)
        • Monitoring в CentOS (67)
        • Virtualization в CentOS/ Red Hat/ Fedora (42)
          • Docker (23)
          • Kubernetes (6)
          • KVM (5)
          • OpenVZ (2)
          • Vagrant (5)
          • VirtualBox (6)
          • VMWare (3)
          • ArgoCD (1)
          • Concourse (1)
          • Gitlab (1)
          • Jenkinks (4)
          • Spinnaker (1)
          • Apache (35)
          • Cherokee (1)
          • DNS (3)
          • FTP (10)
          • Nginx (33)
          • PHP (34)
          • Proxy для RedHat’s (2)
          • Tomcat (2)
          • Voice (2)
          • Панели управления в CentOS/Red Hat/Fedora (27)
          • Прокси сервер на CentOS/RHEL/Fedora (4)
          • Установка и настройка почты на CentOS/RHEL/Fedora (14)
          • Хранилища (clouds) (1)

          соц сети

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Архив новостей

          Свежие записи

          Свежие комментарии

          • Глеб к записи Установка Adobe Flash Player в Debian/Ubuntu/Mint
          • Максим к записи Заблокировать User Agents используя Nginx
          • Денис к записи Как включить EPEL репозиторий на CentOS
          • Гость к записи Закомментировать/Раскомментировать строки vi/vim в Unix/Linux
          • Sergey к записи Установка и настройка OpenVPN сервера на Debian/Ubuntu/Linux Mint

          Источник

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