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
GAD3R
61k30 gold badges126 silver badges189 bronze badges
asked Dec 13, 2017 at 9:13
8
From the comment:
sudo update-alternatives --config python
Will show you an error:
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
Then run :
sudo update-alternatives --config python
Set python3.6 as default.
Or use the following command to set python3.6 as default:
sudo update-alternatives --set python /usr/bin/python3.6
answered Dec 14, 2017 at 12:11
GAD3RGAD3R
61k30 gold badges126 silver badges189 bronze badges
14
You can achieve this by applying below simple steps —
-
Check python version on terminal:
python --version
-
Execute this command to switch to python 3.6:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1
-
Check python version:
python --version
-
Done.
Kusalananda♦
307k35 gold badges598 silver badges896 bronze badges
answered Feb 2, 2019 at 9:37
Vineet JainVineet Jain
8036 silver badges2 bronze badges
2
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
answered May 25, 2019 at 18:03
IRSHADIRSHAD
5375 silver badges3 bronze badges
3
Using these commands can help you:
- check the version of python:
ls /usr/bin/python*
- alias:
alias python='/usr/bin/pythonxx'
(add this to. ~/.bashrc
) - re-login or source
. ~/.bashrc
- check the python version again:
python --version
answered Nov 8, 2018 at 11:44
NewtNewt
3692 silver badges4 bronze badges
3
First check that you have a python3.6 folder?
ls /usr/bin/python3.6
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:
python3 --version
Stewart
11.1k1 gold badge36 silver badges67 bronze badges
answered May 21, 2019 at 10:29
mmblackmmblack
1471 silver badge4 bronze badges
3
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
answered Dec 4, 2018 at 11:13
1
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.
EDIT :
As Mikael Kjær pointed out, this is a misconfiguration of ansible with your system.
As seen here :
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
answered Dec 13, 2017 at 9:27
3
update-alternatives is to change system symlinks to user-defined/admin-defined symlinks.
If you have multiple versions of python3 installed in your system and want to control which python3 version to invoke when python3 is called. Do the following
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 2
Run below command if you want to change priority in the future.
update-alternatives --config python3
Explanation:-
sudo update-alternatives --install <symlink_origin> <name_of_config> <symlink_destination> <priority>
You can go on change name_of_config to python4, but then you have to invoke update-alternatives —config with python4 to reconfigure.
Using this approach you are able to control system python version and python3 version separately.
answered Mar 13, 2019 at 20:02
1
You can change the simbolic link by ln -sf python3.6 python3
inside /usr/bin
. With this when you call python3
it will execute python3.6
answered May 21, 2019 at 10:42
Python – это язык высокоуровневый язык программирования, широко используемый в данное время.
Он доступен для всех популярных операционных систем.
Вы можете установить более одной версии Python на одной системе.
После установки нескольких версий Python вы можете переключить Python по умолчанию с помощью инструмента update-alternatives.
Как переключаться между несколькими версиями PHP в Ubuntu
Всем разработчикам Python рекомендуется использовать виртуальную среду для приложений. Это обеспечивает изолированную среду для приложения с определенной версией Python.
Переключение версии Python на Ubuntu и Debian
Инструмент командной строки update-alternatives предназначен для создания и поддержки символических ссылок для команд по умолчанию.
С его помощью мы можем легко переключать команды на разные версии.
В данном учебнике на системе Debian установлены Python3.9 и Python2.7.
Мы создадим группу для обеих команд и установим символические ссылки.
Создайте симлинк из /usr/bin/python2.7 в /usr/bin/python и задайте имя группы как “python”.
Позже имя группы будет использоваться для переключения ссылок.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
Измените ссылку симлинка /usr/bin/python3.9 на /usr/bin/python и установите имя группы на “python”.
Имя группы должно быть одинаковым для всех версий python.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 2
Вывод:
update-alternatives: using /usr/bin/python3.9 to provide /usr/bin/python (python) in auto mode
Повторите шаг 2, чтобы добавить в группу еще одну версию Python, которая уже установлена в вашей системе.
На данном этапе вы добавили два бинарника python в группу с именем “python”.
Теперь вы можете легко переключиться на любую версию с помощью следующих команд.
Здесь “python” – это имя группы, определенное в приведенных выше командах.
sudo update-alternatives --config python
Вывод: [Выберите опцию]
There are 2 choices for the alternative python (providing /usr/bin/python). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/bin/python3.9 2 auto mode * 1 /usr/bin/python2.7 1 manual mode 2 /usr/bin/python3.9 2 manual mode Press to keep the current choice[*], or type selection number:
В приведенном выше выводе Python 2.7 установлен в качестве текущей версии.
Чтобы изменить ее на Python 3.9, нужно ввести 0 или 2 и нажать Enter.
Вот и все.
Текущая версия Python в вашей системе изменена.
Просто введите следующую команду для просмотра корректной активной версии Python
python -V
Вывод:
Python 3.9.2
Вы можете добавить несколько версий Python в группу (Шаги: 01 и 02) и легко переключаться между ними.
Заключение
В этом руководстве вы узнали о переключении версий Python по умолчанию в системах Ubuntu и Debian Linux.
Вместо переключения версий вы также можете настроить виртуальную среду Python для своих приложений.
см. также:
- Как переключаться между TTY без использования функциональных клавиш в Linux
- Как переключаться между различными версиями команд в Linux
- 🐍 Как поменять местами две переменные в Python?
- 🐍 Как отобразить доступные версии пакета Python
Разработчики python не сделали поддержку версий и это не очень хорошо. Появляется ряд проблем, а именно с версиями ПО. Одни утилиты требуют версию 2.7.х, другие 3.4.х. И я хотел бы в своей статье, рассказать как можно использовать несколько версий или переключить версию python в Unix/Linux.
Переключить версию python в Unix/Linux
Сейчас по умолчанию, во многих Unix/Linux ОС используется питон 2.6. Чтобы проверить какая версия питона используется в системе, выполните:
$ python -V Python 2.6
Выполним установку python:
Обновить Python до последней версии в Unix/Linux
Установка pip/setuptools/wheel в Unix/Linux
Так же, посмотрим:
$ ls -al /usr/local/bin/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 — использование алиаса===-
Один из самых простых способов — это использовать алиасы. Открываем файл:
# vim ~/.bashrc
И, прописываем сам алиас на нужную версию питона:
alias python='/usr/local/bin/python3.6'
Чтобы изменения вступили в силу, выполняем:
$ . ~/.bashrc
После этого, можно проверять версию:
$ 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 -V Python 3.6.1
Для переключения между вышеперечисленными версиями python теперь достаточно просто:
# alternatives --config python
Чтобы удалить питон с alternatives, используем:
# update-alternatives --remove python /usr/local/bin/python3.6
Как-то так! На этому у меня все, статья «Переключить версию python в Unix/Linux» завершена.
I was trying to set default python version to python3
in Ubuntu 16.04
. By default it is python2
(2.7). I followed below steps :
update-alternatives --remove python /usr/bin/python2
update-alternatives --install /usr/bin/python python /usr/bin/python3
but I’m getting the following error for the second statement,
rejeesh@rejeesh-Vostro-1015:~$ update-alternatives --install /usr/bin/python python /usr/bin/python3
update-alternatives: --install needs <link> <name> <path> <priority>
Use 'update-alternatives --help' for program usage information.
SuperStormer
4,8625 gold badges23 silver badges34 bronze badges
asked Feb 1, 2017 at 17:57
RejeeshChandranRejeeshChandran
4,0583 gold badges23 silver badges32 bronze badges
8
The second line mentioned can be changed to
[sudo] update-alternatives --install /usr/bin/python python /usr/bin/python3 10
This gives a priority of 10 for the path of python3
.
The disadvantage of alternatively editing .bashrc
is that using the commands with sudo
will not work.
Nico Schlömer
50.9k26 gold badges190 silver badges237 bronze badges
answered May 14, 2018 at 13:10
10
EDIT:
I wrote this when I was young and naive, update-alternatives
is the better way to do this. See @Pardhu’s answer.
Outdated answer:
Open your .bashrc file
nano ~/.bashrc
. Typealias python=python3
on to a new line at the top of the file then save the file with ctrl+o
and close the file with ctrl+x. Then, back at your command line type
source ~/.bashrc
. Now your alias should be permanent.
Nico Schlömer
50.9k26 gold badges190 silver badges237 bronze badges
answered Feb 1, 2017 at 18:17
SteampunkerySteampunkery
3,8412 gold badges20 silver badges28 bronze badges
9
To change Python 3.6.8 as the default in Ubuntu 18.04 to Python 3.7.
Install Python 3.7
Steps to install Python3.7 and configure it as the default interpreter.
-
Install the python3.7 package using apt-get
sudo apt-get install python3.7
-
Add Python3.6 & Python 3.7 to
update-alternatives
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
-
Update Python 3 to point to Python 3.7
sudo update-alternatives --config python3
Enter 2 for Python 3.7 -
Test the version of python
python3 --version
Python 3.7.1
Alvin Sartor
2,0973 gold badges21 silver badges36 bronze badges
answered Aug 24, 2019 at 23:03
5
If you have Ubuntu 20.04 LTS (Focal Fossa) you can install python-is-python3
:
sudo apt install python-is-python3
which replaces the symlink in /usr/bin/python
to point to /usr/bin/python3
.
answered May 18, 2020 at 20:12
silviotsilviot
4,4755 gold badges38 silver badges51 bronze badges
3
To change to python3, you can use the following command in terminal alias python=python3
.
answered Feb 1, 2017 at 18:00
DanteVoronoiDanteVoronoi
1,1031 gold badge12 silver badges20 bronze badges
2
Update:
Since Ubuntu 20.04, the python3 is the default version, but still, python is not registered as python3 by default. In order to make that happen, you can simply do :
sudo apt install python-is-python3
For more information you can check this out.
Old way:
Do
cd ~
gedit .bash_aliases
then write either
alias python=python3
or
alias python='/usr/bin/python3'
Save the file, close the terminal and open it again.
You should be fine now! Link
answered Sep 15, 2017 at 18:34
HosseinHossein
23.3k34 gold badges117 silver badges217 bronze badges
1
A simple safe way would be to use an alias. Place this into ~/.bashrc file:
if you have gedit editor use
gedit ~/.bashrc
to go into the bashrc file and then at the top of the bashrc file make the following change.
alias python=python3
After adding the above in the file. run the below command
source ~/.bash_aliases or source ~/.bashrc
example:
$ python —version
Python 2.7.6
$ python3 —version
Python 3.4.3
$ alias python=python3
$ python —version
Python 3.4.3
answered Feb 9, 2018 at 10:32
KhanKhan
1,21411 silver badges11 bronze badges
0
Just follow these steps to help change the default python to the newly upgrade python version. Worked well for me.
sudo apt-install python3.7
Install the latest version of python you wantcd /usr/bin
Enter the root directory where python is installedsudo unlink python
orsudo unlink python3
. Unlink the current default pythonsudo ln -sv /usr/bin/python3.7 python
Link the new downloaded python versionpython --version
Check the new python version and you’re good to go
answered Dec 30, 2019 at 9:19
At First Install python3 and pip3
sudo apt-get install python3 python3-pip
then in your terminal run
alias python=python3
Check the version of python in your machine.
python --version
answered Nov 25, 2019 at 18:32
As an added extra, you can add an alias for pip as well (in .bashrc or bash_aliases):
alias pip=’pip3′
You many find that a clean install of python3 actually points to python3.x so you may need:
alias pip=’pip3.6′
alias python=’python3.6′
answered Mar 28, 2018 at 14:28
ParaicParaic
1371 silver badge6 bronze badges
This is a simple way that works for me.
sudo ln -s /usr/bin/python3 /usr/bin/python
You could change /usr/bin/python3
for your path to python3 (or the version you want).
But keep in mind that update-alternatives
is probably the best choice.
answered Jan 15, 2021 at 14:18
cbcramcbcram
1652 silver badges6 bronze badges
As it says, update-alternatives --install
needs <link> <name> <path> and <priority> arguments.
You have link (/usr/bin/python
), name (python
), and path (/usr/bin/python3
), you’re missing priority.
update-alternatives --help
says:
<priority> is an integer; options with higher numbers have higher priority in automatic mode.
So just put a 100
or something at the end
answered Feb 1, 2017 at 19:30
get python path from
ls /usr/bin/python*
then set your python version
alias python="/usr/bin/python3"
answered Oct 16, 2018 at 4:26
To change Python 3.6.8 as the default in Ubuntu 18.04 from Python 2.7 you can try the command line tool update-alternatives
.
sudo update-alternatives --config python
If you get the error «no alternatives for python» then set up an alternative yourself with the following command:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2
Change the path /usr/bin/python3
to your desired python version accordingly.
The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.6.8
and as a result the /usr/bin/python3.6.8
was set as default python version automatically by update-alternatives command.
we can anytime switch between the above listed python alternative versions using below command and entering a selection number:
update-alternatives --config python
answered Jun 27, 2020 at 12:24
For another non-invasive, current-user only approach:
# First, make $HOME/bin, which will be automatically added to user's PATH
mkdir -p ~/bin
# make link actual python binaries
ln -s $(which python3) python
ln -s $(which pip3) pip
python
pip
will be ready in a new shell.
answered Mar 22, 2019 at 8:52
tdihptdihp
2,2792 gold badges22 silver badges40 bronze badges
Simply remove python-is-python2
:
sudo apt purge python-is-python2
And install python-is-python3
:
sudo apt install python-is-python3
It will automate the process of transition to new python3. Optionally you can get rid of remaining packages later:
sudo apt autoremove && sudo apt autoclean
answered May 25, 2020 at 8:22
0
Set priority for default python in Linux terminal by adding this:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
Here, we set python3
to have priority 10 and python2
to priority 1. This will make python3
the default python. If you want Python2 as default then make a priority of python2 higher then python3
answered Nov 6, 2020 at 4:52
~$ sudo apt-get install python3.9
/usr/bin$ cd /usr/bin
/usr/bin$ sudo unlink python3
/usr/bin$ sudo ln -sv /usr/bin/python3.9 python3
/usr/bin$ python3 --version
Python 3.9.5
/usr/bin$ pip3 --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.9)
answered Jan 3, 2022 at 3:46
devpdevp
1,9582 gold badges15 silver badges26 bronze badges
2
The best way in ubuntu 18.04 which will work for all users is
sudo vim /etc/bash.bashrc
add lines
alias python=python3
alias pip=pip3
Save the changes and restart .
After restart what ever version of python 3 you have in the system along with python 2.7 will be taken as default. You could be more specific by saying the following in alias if you have multiple version of python 3.
sudo vim /etc/bash.bashrc
add lines
alias python=python3.6
alias pip=pip3.6
answered Mar 22, 2019 at 10:12
Mian Asbat AhmadMian Asbat Ahmad
3,14810 gold badges44 silver badges68 bronze badges
sudo rm /usr/bin/python3 #remove existing link
sudo ln /usr/bin/python3.8 /usr/bin/python3 # create a new link to the version of your choice
answered Oct 1, 2021 at 9:11
1
You didn’t include the priority argument
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 5
You can replace 5 with any priority you want. A higher priority alternative takes precedence over lower priority.
answered Sep 2, 2020 at 12:26
If there is a possibility to use particular python version directly, I would go for it compared to update-alternatives
and alias
solution.
Ex.
python3.6 -m pip install pytest
ptyhon3.6 -m pytest test_sample.py
-m
executes particular module for that particular python version.
The first line will install pytest for for that particular version and user in possible location /home/user/.local/lib/python3.5/site-packages
answered Dec 15, 2021 at 1:21
JanPoJanPo
1851 silver badge8 bronze badges
At first, Make sure Python3 is installed on your computer
Go to your terminal and type:
cd ~/
to go to your home directory
If you didn’t set up your .bash_profile
yet, type touch .bash_profile
to create your .bash_profile.
Or, type open -e .bash_profile
to edit the file.
Copy and save alias python=python3
in the .bash_profile.
Close and reopen your Terminal. Then type the following command to check if Python3 is your default version now:
python --version
You should see python 3.x.y is your default version.
Cheers!
answered Sep 21, 2019 at 19:13
1
I would like to set python 3.8 as default on my PC
Thinkpad X230
Ubuntu 20.04
I tried setting an alias
gt@gt-ThinkPad-X230:~$ alias python='usr/bin/python3.8'
Q: Does this alter a .bashrc file? If so, which?
~/.bashrc?
another?
if so, which?
gt@gt-ThinkPad-X230:~$ python --version
bash: usr/bin/python3.8: No such file or directory
Complains it cannot find /usr/bin/python3.8, buuuuut:
gt@gt-ThinkPad-X230:~$ ls /usr/bin/python*
/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?
asked Sep 5, 2020 at 15:55
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.
answered Sep 5, 2020 at 17:56
volferinevolferine
7011 gold badge4 silver badges4 bronze badges
3
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:
sudo update-alternatives --set python /usr/bin/python3.8
This will ensure you have the version of python in use that you intend, everywhere.
answered Sep 5, 2020 at 16:24
5
Check the installed versions of Python:
ls /usr/bin/python*
Then, create the alternatives:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2
Then, choose the version you want:
sudo update-alternatives --config python
You can easily switch between default Python versions.
answered Feb 18, 2021 at 16:38
1
You should be able to do it in a command shell by typing:
alias python=python3.8
To make it permanent you need to open up ~/.bashrc and add that line to the end of it. Should be as simple as that! Keep in mind this only works on a per user basis, which may or may not be what you want.
The other other thing that I notice with your attempt, is that your missing the leading /, so it should be reading as:
alias python='/usr/bin/python3.8'
without that leading forward / it may be trying to use a relative path.
answered Sep 5, 2020 at 16:25
NebriNebri
2291 silver badge8 bronze badges
1
In this article, we will upgrade to python 3.10 and configure it as the default version of python in Ubuntu 18.04 and 20.04 LTS.
The current stable version of python was released on 06 Dec. 2021. Many ubuntu users are facing problems during upgrading python to the latest version. Python 3.9 is available as default when we install Ubuntu 20.04 LTS and Python 3.8 is available in Ubuntu 18.04. Python 3.10.0 is not available in default Ubuntu 18.04 and 20.04 repositories.
- Also Read: How to upgrade to Python 3.9 on Ubuntu 18.10
So let’s start with checking the currently installed version of Python on your system.
python3 -V
As seen in the image above, my currently installed Python version is 3.8.10 but yours may differ.
Install Python 3.10
Follow the simple steps to install and configure Python 3.10
Step 1: Add the repository and update
Latest Python 3.10 is not available in Ubuntu’s default repositories. So, we have to add an additional repository. On launchpad repository named deadsnakes is available for Python Packages.
Add the deadsnakes repository using the below commands.
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
Update the package list using the below command.
apt-get update
Verify the updated Python packages list using this command.
apt list | grep python3.10
As seen in the image above, Now we have Python 3.10 available for installation.
Step 2: Install the Python 3.10 package using apt-get
install Python 3.10 by using the below command :
sudo apt-get install python3.10
Step 3: Add Python 3.8 & Python 3.10 to update-alternatives
Add both old and new versions of Python to Update Alternatives.
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 2
Step 4: Update Python 3 for point to Python 3.10
By default, Python 3 is pointed to Python 3.8. That means when we run python3 it will execute as python3.8 but we want to execute this as python3.10.
Type this command to configure python3:
sudo update-alternatives --config python3
You should get the above output. Now type 2 and hit enter for Python 3.10. Remember the selected number may differ so choose the selection number which is for Python 3.10.
Step 5: Test the version of python
Finally, test the current version of python by typing this :
python3 -V
You should get Python 3.10 as output.
In this article, we learn how to upgrade python to the latest version that is 3.10 in Ubuntu 20.04 and 18.10.
Share your thoughts in the comment section. Happy Learning …!!
- Also Read: How to Install Asterisk 16 on Ubuntu 18.04 LTS
how to install python in ubuntu, how to install python in ubuntu 20.04, how to upgrade python in ubuntu, install latest python in ubuntu, install python 3.10, install python 3.10 ubuntu, install python in ubuntu, python 3.10, python in ubuntu 18, python in ubutnu, ubuntu 18.04 lts bionic beaver, Ubuntu 20.04 LTS, upgrade python in ubuntu, upgrade to python 3.10 ubuntu 18.04, upgrade to python 3.10 ubuntu 20.04
This div height required for enabling the sticky sidebar
Последнее обновление: 16.12.2022
На одной рабочей машине одновременно может быть установлено несколько версий Python. Это бывает полезно, когда идет работа с некоторыми внешними библиотеками, которые поддерживают разные версии python, либо в силу каких-то
других причин нам надо использовать несколько разных версий. Например, на момент написания статьи последней и актуальной является версия Python 3.11.
Но, допустим, необходимо также установить версию 3.10, как в этом случае управлять отдельными версиями Python?
Windows
На странице загрузок https://www.python.org/downloads/ мы можем найти ссылку на нужную версию:
И также загрузить ее и установить:
Чтобы при использовании интерпретатора Python не прописывать к нему весь путь, добавим при установке его в переменные среды. Но здесь надо учитывать, что в переменных среды
может содержаться несколько путей к разным интерпретаторам Python:
Та версия Python, которая находится выше, будет версией по умолчанию. С помощью кнопки «Вверх» можно нужную нам версию переместить в начало, сделав версией по умолчанию.
Например, в моем случае это версия 3.11. Соответственно, если я введу в терминале команду
или
то консоль отобразит версию 3.11:
C:python>python --version Python 3.11.0
Для обращения к версии 3.10 (и всем другим версиям) необходимо использовать указывать номер версии:
C:python>py -3.10 --version Python 3.10.9
например, выполнение скрипта 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:
sudo apt-get install python3.10 sudo apt-get install python3.11
Одна из версий является версий по умолчанию. И для обращения к ней достаточно прописать python3, например, проверим версию по умолчанию:
Для обращения к другим версиям надо указывать подверсию:
python3.10 --version python3.11 --version
Например, выполнение скрипта hello
с помощью версии Python 3.10:
Но может сложиться ситуация, когда нам надо изменить версию по умолчанию. В этом случае применяется команда update-alternatives для связывания
определенной версии Python с командой python3. Например, мы хотим установить в качестве версии по умолчанию Python 3.11. В этом случае последовательно выполним следующие команды:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1 sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2
Числа справа указывают на приоритет/состояние. Так, для версии 3.11 указан больший приоритет, поэтому при обращении к python3
будет использоваться именно версия 3.11 (в моем случае это Python 3.11.0rc1)
С помощью команды
sudo update-alternatives --config python3
можно изменить версию по умолчанию
Last Updated: 2022-08-11
Linux systems come with Python install by default, but, they are usually not the latest. Python also cannot be updated by a typical apt upgrade
command as well.
To check the version of Python installed on your system run
python
keyword is used for Python 2.x versions which has been deprecated
In this guide we will
- Update Python to the latest version
- Fix pip & other Python related issues
- While doing the above two, ensure your Ubuntu which is heavily dependent on Python does not break
Updating Python to the latest version
Ubuntu’s default repositories do not contain the latest version of Python, but an open source repository named deadsnakes
does.
Python3.10 is not officially available on Ubuntu 20.04, ensure you backup your system before upgrading.
Step 1: Check if Python3.10 is available for install
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
Check if Python 3.10 is available by running
apt list | grep python3.10
This will produce the below result, if you see python3.10 it means you can install it
Step 2: Install Python 3.10
Now you can install Python 3.10 by running
sudo apt install python3.10
Now though Python 3.10 is installed, if you check the version of your python by running python3 --version
you will still see an older version. This is because you have two versions of Python installed and you need to choose Python 3.10 as the default.
Step 3: Set Python 3.10 as default
Steps beyond here are tested on Ubuntu 20.04 in VM & WSL2, but are experimental , proceed at your own risk.
Changing the default alternatives for Python will break your Gnome terminal. To avoid this, you need to edit the gnome-terminal
configuration file.
Open the terminal and run:
sudo nano /usr/bin/gnome-terminal
In first line, change #!/usr/bin/python3
to #!/usr/bin/python3.8
. Press Ctrl +X
followed by enter
to save and exit.
Then save and close the file.
Next, update the default Python by adding both versions to an alternatives by running the below
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 2
Now run
sudo update-alternatives --config python3
Choose the selection corresponding to Python3.10 (if not selected by default).
Now run python3 --version
again and you should see the latest Python as the output.
Fix pip and disutils errors
Installing the new version of Python will break pip
as the distutils
for Python3.10 is not installed yet.
Fix Python3-apt
Running pip
in terminal will not work, as the current pip is not compatible with Python3.10 and python3-apt will be broken, that will generate an error like
Traceback (most recent call last):
File "/usr/lib/command-not-found", line 28, in <module>
from CommandNotFound import CommandNotFound
File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
from CommandNotFound.db.db import SqliteDatabase
File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
import apt_pkg ModuleNotFoundError: No module named 'apt_pkg'
To fix this first remove the current version of python3-apt by running
sudo apt remove --purge python3-apt
Then do some cleanup
DO NOT RUN sudo apt autoremove
as it will remove several packages that are required. This may break your system if you’re using GUI, if you’re on WSL2 you can proceed.
Finally, reinstall python3-apt
by running
sudo apt install python3-apt
Install pip & distutils
Running pip
will still throw an error pip: command not found
. We need to install the latest version of pip compatible with Python 3.10.
Also, if try to manually install the latest version of pip, it will throw an error like
ImportError: cannot import name 'sysconfig' from 'distutils'
(/usr/lib/python3.10/distutils/__init__.py)
Or you might also see an error stating No module named 'distutils.util'
. This is because the distutils
module is not installed yet, to install run the below command
sudo apt install python3.10-distutils
Now you can install pip
by running
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
sudo python3.10 get-pip.py
If you get an error like
bash: curl: command not found
then you need to install curl first by runningsudo apt install curl
Now you can run pip
and you should see the output of pip --version
Fix pip-env errors when using venv
When you try to create a new virtual environment using python -m venv env
, you may into the following error.
Error: Command '['/path/to/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
You can fix this by reinstalling venv by running
sudo apt install python3.10-venv
All should be done now. It is complicated, but this is how you update Python to latest version.
If you have oh-my-zsh installed, you can avoid typing out python3
by running
echo "alias py=/usr/bin/python3" >> ~/.zshrc
echo "alias python=/usr/bin/python3" >> ~/.zshrc
Now you can run your files with py
or python
.