Как по умолчанию использовать python 3 linux
Перейти к содержимому

Как по умолчанию использовать python 3 linux

  • автор:

Changing Default Python version in Ubuntu

Dilip Singh

Every Ubuntu version comes with a default python version. for example: Ubuntu 20 LTS came with Python 3.8.

If you want to use different python version you can do this with update-alternatives.

Ex. If you have a later/newer version of Python like 3.8 and you want to set earlier/older version like 3.7 as default.

Step-1: Check Python version with

for purpose of this example, I assume you have python 3.8 installed in you system.

Step-2: Install the python version to set as default.

Step-3: run the update-alternatives command to add both python version in alternatives. and set higher priority to desire version.

Now, Because we set the higher priority to python 3.7, it is the default python version now, but you can see and change the version as you need by this command.

If Something went Wrong!

In some cases (e.g., installing or updating certain packages), you’ll get an error message if you’ve run the commands above. To update these packages, you’ll have to temporarily undo these changes. Here’s how to do that:

  1. Remove all alternatives.

2. Set things as they are before.

Setup again

Once you’re done updating these packages, execute the commands at the top to set python3.7 as the default again.

Hi, I’m Dilip Singh, a computer science student, if you want to say or share anything with me about my post and if anything not working find me on

Setting the Default python to python3

In this tutorial, let’s look at how to set the default Python in our system based on our preferred Python version. Most Linux distros usually have the latest stable release of Python included as the default, and in older systems, the deprecated Python2.* is the default.

We’ll see how we can change the default Python using the alias and update-alternatives commands.

2. Setting Default Using the alias Command

Before we make any changes, let’s check which version of Python is available in our system:

In the above snippet, the python command with the –version option shows our system’s currently set default Python version. Likewise, python3 displays whichever version of Python3 is installed.

To check for Python2, we run python2 –version. Alternatively, we can run python -V to get the same result.

The alias command lets us create shortcuts for commands or override the default options for the existing commands. Assuming we’ve installed Python3.8 in the /usr/bin directory and want it to be our default Python, we can use the alias command:

In this example, we’ve overridden the default Python and set our preferred one:

set default python

Using an alias, we can set both python and python3 commands to the same path. However, upon shutdown or rebooting, the setting isn’t retained. For this reason, to make the change permanent, we need to edit the bash_aliases file by appending our alias to it:

We then save the file and activate the alias:

It’s important not to add our alias to the

/.bashrc file. This is because if we do so, we won’t be able to use the aliased command with sudo.

Again, let’s check the version and find out what is the default version set:

3. Using the update-alternatives Command

Now, we’ll look at how we can set the default Python version to whatever version we want using the update-alternatives command. We use this command to maintain symbolic links determining default commands.

Let’s say we’ve got several versions of Python installed. For instance, let’s assume these are the versions we currently have:

Next, suppose we want the Python in /usr/local/bin/python3.11 set as the default. We’ll use the update-alternatives command following this syntax:

We should note that flags with higher priority numbers have higher precedence in automatic mode:

Depending on the Python version we want to be the default, we select a number shown and then click on the enter key.

Once more, let’s check if the Python version has changed to that contained in the path we chose:

If there’s only a single link, we’ll get this error:

Additionally, we’ll also get this error if we don’t set the priority number:

4. Conclusion

In this article, we’ve looked at the two ways to set the default Python version of our preference. We also discussed some common errors we encounter while using the update-alternatives command.

Как по умолчанию использовать python 3 linux

На одной рабочей машине одновременно может быть установлено несколько версий Python. Это бывает полезно, когда идет работа с некоторыми внешними библиотеками, которые поддерживают разные версии python, либо в силу каких-то других причин нам надо использовать несколько разных версий. Например, на момент написания статьи последней и актуальной является версия Python 3.11 . Но, допустим, необходимо также установить версию 3.10 , как в этом случае управлять отдельными версиями Python?

Windows

На странице загрузок https://www.python.org/downloads/ мы можем найти ссылку на нужную версию:

Управление несколькими версиями Python

И также загрузить ее и установить:

Установка разных версий Python на Windows

Чтобы при использовании интерпретатора Python не прописывать к нему весь путь, добавим при установке его в переменные среды. Но здесь надо учитывать, что в переменных среды может содержаться несколько путей к разным интерпретаторам Python:

Установка разных версий Python на Windows в переменные среды

Та версия Python, которая находится выше, будет версией по умолчанию. С помощью кнопки «Вверх» можно нужную нам версию переместить в начало, сделав версией по умолчанию. Например, в моем случае это версия 3.11. Соответственно, если я введу в терминале команду

Для обращения к версии 3.10 (и всем другим версиям) необходимо использовать указывать номер версии:

например, выполнение скрипта hello.py с помощью версии 3.10:

Подобным образом можно вызывать и другие версии Python.

MacOS

На MacOS можно установить разные версии, например, загрузив с официального сайта пакет установщика для определенной версии.

Для обращения к определенной версии Python на MacOS указываем явным образом подверсию в формате python3.[номер_подверсии] . Например, у меня установлена версия Python 3.10. Проверим ее версию:

Аналогично обращении к версии python3.9 (при условии если она установлена)

К примеру выполнение скрипта hello.py с помощью версии python 3.10:

Linux

На Linux также можно установить одновременно несколько версий Python. Например, установка версий 3.10 и 3.11:

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

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

Например, выполнение скрипта hello с помощью версии Python 3.10:

Но может сложиться ситуация, когда нам надо изменить версию по умолчанию. В этом случае применяется команда update-alternatives для связывания определенной версии Python с командой python3. Например, мы хотим установить в качестве версии по умолчанию Python 3.11. В этом случае последовательно выполним следующие команды:

Числа справа указывают на приоритет/состояние. Так, для версии 3.11 указан больший приоритет, поэтому при обращении к python3 будет использоваться именно версия 3.11 (в моем случае это Python 3.11.0rc1)

How can I change the default python on my Ubuntu 20.04 to Python3.8?

Complains it cannot find /usr/bin/python3.8, buuuuut:

/usr/bin/python /usr/bin/python3.8 /usr/bin/python3-pasteurize /usr/bin/python2 /usr/bin/python3.8-config /usr/bin/python3-unidiff /usr/bin/python2.7 /usr/bin/python3-config /usr/bin/python3 /usr/bin/python3-futurize

How do I get bash to find see /usr/bin/python3.8?

4 Answers 4

The correct way is sudo apt install python-is-python3 — it effectively does a symlink, but it also keeps pace with future updates; so if your ubuntu distribution moves to say Python 3.9, the manual symlink will no longer work, but the package makes sure it is still valid.

Firstly to answer your question, your approach should work, I think the path you’ve given in your alias needs the / preceding the path so the command should be alias python=’/usr/bin/python3.8′ , this would indeed need to go into your

/.bashrc file assuming you are using bash.

Secondly, Ubuntu has a really nice method of setting default binaries globally rather than messing with dot config files as depicted here: update-alternatives

a better solution may be to simply run:

This will ensure you have the version of python in use that you intend, everywhere.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *