- How to install Python 3 and set defaults on Centos 7
- II. Implementation Guide
- Step 1: SSH into your VPS
- Step 2: Check the version of Python you are using
- Step 3: Update the Yum . management tool
- Step 4: Install Python 3
- Step 5: Set Python 3 as Default
- III. Conclude
- Русские Блоги
- Установите python3.6 под centos7 и измените его на среду python по умолчанию
- How to make python3.7 default
- Quick summary
- Further details
- Bash alias
- update-alternatives
- Testing
- Fixing your system if you ran the update-alternatives method
- How to change python default version from 2.7 to 3.7 on RHEL 7
- 3 Answers 3
How to install Python 3 and set defaults on Centos 7
Python is a powerful, high-level, object-oriented programming language, created by Guido van Rossum. It’s easy to learn and is emerging as one of the best introductory programming languages for first-timers. Python is completely dynamically typed and uses automatic memory allocation. Python has powerful high-level data structures and a simple yet effective approach to object-oriented programming. Python’s command syntax is a huge plus as its clarity, ease of understanding, and flexible typing make it rapidly becoming an ideal language for scripting and application development in a wide variety of fields, in most areas. all platforms.
You can learn more about Python through each version as well as the structure and operating principles .
II. Implementation Guide
To install Python 3 you can follow the following 3 installation steps.
Step 1: SSH into your VPS
First you need to SSH into your VPS with Root rights.
Step 2: Check the version of Python you are using
By default Python installed on Centos 7 will be Python 2.7.x version, you use the following command to check the version.
So currently this VPS of mine is using Python version 2.7.
So to upgrade to Python 3 version, you continue to step 3.
Step 3: Update the Yum . management tool
yum -y update (Update yum) yum -y install yum-utils (Install yum utils) yum -y groupinstall development (installs CentOS development tools that help build and compile software from source code.)
Step 4: Install Python 3
To check and download the latest Python versions, you can visit the homepage
- Since the standard yum repos don’t have the latest python release, we will install the IUS (Inline with Upstream Stable) which will have the latest packages. You run the command.
yum install \ https://repo.ius.io/ius-release-el7.rpm \ https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install python36u-pip
yum -y install python36u-devel
Step 5: Set Python 3 as Default
Although we have successfully installed Python 3, the VPS will still use Python version 2.7.5 as default. To change the default version, do the following.
- Check the location where Python 3 has just been installed, before that I installed Python 3.6 version, so I will use the following command.
The path will display as follows
which python3.6 /usr/bin/python3.6
This part means that we will add Alias configuration so that when calling the python command, the system will load the specified path (here is Python version 3.6). You open and edit the bash_profile file with the command.
Remember to replace /usr/bin/python3.6 with the path on your VPS.
alias python = '/usr/bin/python3.6'
After editing, tap :wq to Save the configuration.
III. Conclude
Thus, in this article, We showed you how to install Python 3 and at the same time showed you how to set this new version of Python as the system default. With this upgrade, you will be able to use more new Packages from Python because each new Package is developed they have conditions attached to the supported version. Hope this article will help you to install successfully.!
Русские Блоги
Установите python3.6 под centos7 и измените его на среду python по умолчанию
Среда, которая поставляется с centos, — это python2, поэтому python3 необходимо установить самостоятельно. В этой статье кратко рассказывается об установке и модификации python3.6 в среду python по умолчанию.
Здесь мы используем установку yum, первый этап подготовки (вы, конечно, думаете, что этого достаточно, или можете сразу пропустить его):
2. Затем установите yum-utils, набор утилит и плагинов, расширяющих и дополняющих yum:
sudo yum -y install yum-utils
Установить python3
sudo yum -y install epel-release
2. Установите исходный код программного обеспечения IUS, выберите пакет rpm в соответствии с вашей системой:
Пожалуйста, выберите пакет rpm в соответствии с вашей системой:
https://centos6.iuscommunity.org/ius-release.rpm
https://centos7.iuscommunity.org/ius-release.rpm
Система — centos7, затем выбираем источник centos7 и устанавливаем
sudo yum install https://centos7.iuscommunity.org/ius-release.rpm
Три, установите python3.6 с помощью pip3
sudo yum -y install python36u python36u-pip
Здесь установка прошла успешно, конечно, вы также можете проверить версию
Вы можете увидеть папки Python3.6 и pip3 в каталоге / usr / lib /.
Затем, что касается некоторых статей, которые используют Python3.6 для использования команды python3.6 xxx.py, вам необходимо создать мягкую ссылку, использовать python3 xxx для использования Python3.6, здесь не требуетсяПосле компиляции и установки соединение python3 будет автоматически создано в /usr/python3.6/bin, что указывает на python3.6 в каталоге bin., Мы можем вызвать python3.6 прямо из python3
(если вы повторите это, он скажет вам, что символическая ссылка «/ usr / bin / python3» не может быть создана: файл уже существует)
Теперь python2.7 и python3.6 сосуществуют, вам нужно использовать python3.6 для использования python3.6, использовать python2.7 — это python2.7, но когда мы вводим python, мы будем использовать его напрямую python2, это потому, что среда python по умолчанию — python2. Мы можем изменить эту указанную версию по умолчанию. Обратите внимание здесь,Изменение версии по умолчанию не приводит к удалению версии, которая вам не нужна, потому что многие нижние уровни системы полагаются на Python, и ее удаление может привести к сбою в работе системы. Так что принудительное удаление установленного Python и связанного с ним ненадежно, если вы не великий бог, о чем я не говорил.
Изменить несложно, это не что иное, как изменение софт-ссылки. Мое личное понимание таково
Итак, если вы хотите его изменить, он будет выглядеть так
Итак, конкретная операция выглядит следующим образом:
1. Удалите файл ссылки Python в каталоге / usr / bin.
2. После удаления создайте новую связь ссылки:
sudo ln -s /usr/bin/python3 /usr/bin/python
3. Мы можем проверить это, войти в каталог / usr / bin как пользователь root и ввести команду ll Проверьте соответствующую софт-ссылку, найдите python, мы видим, что софт-ссылка изменилась
Конечно, вы также можете напрямую ввести python, используя среду python3
4. Если вы хотите восстановить исходный python2.7, используйте тот же метод, просто
sudo rm -rf /usr/bin/python sudo ln -s /usr/bin/ptyhon2.7 /usr/bin/python
5. Кроме того, поскольку yum использует python2, он может не работать после замены python3, поэтому нам нужно переключиться на пользователя root, чтобы изменить файл конфигурации yum, пока все готово!
vim /usr/bin/yum # Измените #! / Usr / bin / python в заголовке файла на #! / Usr / bin / python2.7 vim /usr/libexec/urlgrabber-ext-down # Измените / usr / bin / python в заголовке файла на /usr/bin/python2.7 vim /usr/bin/yum-config-manager # Измените #! / Usr / bin / python в заголовке файла на #! / Usr / bin / python2.7
Кстати, в каталоге / bin есть то же, что и user / bin. Излишне говорить, что каждый, кто изучал liunx, должен знать
How to make python3.7 default
Whenever you will write python3 it will replace it with python3.7 .
Or you can use command update-alternatives which is preferred i.e:
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
So here python3.7 will have higher priority then python3.6 . Then use:
sudo update-alternatives --config python3
Press the enter key if you are satisfied
Trap for young players: I highly recommend using update-alternatives over the alias-approach, as aliases do not take effect in non-shell environments (also non-interactive shells ignore .bashrc). Take a python-file starting with the shebang #!/usr/bin/env python3 as an example: Run with ./myscript.py it would ignore your alias, while python3 myscript.py would run in python 3.7.1 in your case. Other common cases for ambiguities would be invoking commands via ssh, or from inside a shell-script.
Note that the alternatives variant above replaces /usr/bin/python instead of /usr/bin/python3 , and will cause issues with Python programs which expect python to be Python 2 (which is the case on Debian and derivatives). See also PEP 394 and the Debian Python policy.
On my Ubuntu 18.04 any of the two approaches caused the No module named ‘apt_pkg error and the Terminal to not start. I wanted to use python 3.8.1 instead of python 3.6.9.
I would like to expand on a previous answer as the two approaches given are not equivalent, and one of them can even break the system. The issue is there are two different things one could be trying to do by «changing the default python version».
Quick summary
Do not use update-alternatives to change your default python version, as this will break system applications.
Further details
Bash alias
The first, is that for an interactive shell, one simply wishes to easily open the desired python by writing
This is accomplished by adding the line
to .bashrc . If one is using another shell, add this to the appropriate config file. This also has the advantage that if it causes problems for any reason, one can simply remove the offending line in .bashrc and restart the terminal.
update-alternatives
The second thing one could mean by «changing the default python version», is to change the default python version for all programs, including those not launched from an interactive shell. This is the result of running
$ sudo update-alternatives --config python3
However, if you run this in a clean install of Debian/Ubuntu, you will notice that the command returns
update-alternatives: error: no alternatives for python3
even if you have multiple versions of python 3 installed via apt . There is a very good reason for this.
The problem with the this is that many system applications use python, and depending on the exact distribution, many use python 3. Changing which version is called by the command python3 globally will force these applications to use this version. Although different version of python 3 are largely compatible, there are still features moved and removed between releases. If a system application uses these features, changing python3 to launch a newer version will break the application.
Testing
I created a fresh install of Ubuntu 18.04 in a VM. Adding the bash alias caused no immediate issues.
Using the update-alternatives method caused issues with apt . Specifically, I got
ModuleNotFoundError: No module named 'apt_pkg'
Fixing your system if you ran the update-alternatives method
If we ran update-alternatives and broke apt , we can still fix the system. During my testing, the terminal was still able to be opened. One can go back to the default python by running
$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.X 1000
where 3.X is your systems original python 3 version, and 1000 is just some high priority to make sure it is on top. Then, one can run
$ sudo update-alternatives --config python3
and make sure the original system python is selected. Reboot the system and it will be back to normal.
How to change python default version from 2.7 to 3.7 on RHEL 7
How to change python default version from 2.7 to 3.7 on RHEL 7. Installed python on RHEL7 virtual machine by following this https://tecadmin.net/install-python-3-7-on-centos/ When I check python version it still prints old version.
It would not be advised to replace the base python version as it will break your RHEL system (all base software expecting Python 2.7 will cease to work, such as yum ), but to instead keep the base version for the system to use and install the newer version in a way that does not affect the base version. RedHat has an option to install python3 this way using what they call Software Collections.
3 Answers 3
RHEL 7 and its derivatives depend on Python 2 at a very deep level. If you outright replace Python 2 with 3, you’ll break several of the OS’s core tools.
Even if that were not the case, your question is based on an incorrect premise, being that completely replacing Python 2 with Python 3 is a good idea in the first place. Instead, install both side-by-side.
How? It starts with the fact that one should always call Python 3 as python3 , since that insulates you from the major version compatibility problem. Scripts that assume Python 2 will call it as python in shebang lines and such, so there is not in fact a conflict between the old version and your newer version’s python3 binary and everything that depends on it, as long as your binary Python packages are built properly.
That “if” can bite you: some packagers have created Python 3 packages with a /usr/bin/python or similar, which creates a conflict. These packages are ignoring the standard advice, which allows both to be installed in parallel.
As for getting a non-conflicting Python 3 package for RHEL 7, that’s well covered in another answer on Stack Overflow.