How to install python to ubuntu
How to install python to ubuntu
How to Install Latest Python on Ubuntu 18.04
In this tutorial, we are going to show how to install the latest python on Ubuntu 18.04 machine using the terminal. Also, we will create a virtual environment and a simple program and run it. At the moment of writing this article, the latest stable version of python was 3.6.5 but the process of installing allows you to install the latest version by changing just the version number.
Note that Ubuntu 18.04 has python 3 preinstalled. However, we are going to show how to install it, update and uninstall.
How to install latest python
Before installing the latest version of python check the version of python currently installed on your machine. To do so you can run:
If there are several versions installed on your machine you can run the following command to view all versions:
If you want to install the latest version of python3 on your Ubuntu18 machine you can run:
or if it’s already preinstalled, you can run the command below to update to latest version.
However, if you want to install it manually you can use the source code. To do so, follow the instruction below.
How to install python from source
To install the latest python from source, get the download link of the latest version from python’s official website and download it to your Ubuntu machine. To do so you can run:
Once it is downloaded, extract the archive using the command below:
Change your directory to the newly created Python3.6.5 folder by running:
and run the configure script to check the build
Once the check has been completed run the following commands in the mentioned order to install python 3.6.5
However, if there wasn’t need to use zlib1g-dev package before, you’ll get an error of it’s absence, which will look like this:
To install the missing package run:
After package installation run the sudo make and sudo make install commands once more. After installation is completed check the installed version with the following command:
Output must look like this:
How to update python to latest version
To update python to the latest version, you can run:
or if you have installed manually from source, you must uninstall the previous version and install the latest version or the one you want. The steps of how to do so are described in the section below.
How to uninstall python
To uninstall python from your Ubuntu 18 machine, run:
Note that you cannot mention major python3 version as it is being used by the system, but you can uninstall minor version which is preinstalled on your machine.
If you have installed python from source and need to update it, you must uninstall the previous one and repeat the installation steps which are described above in this article. As this method if installation locates python files in /usr/local/bin path, you must remove python files from that path. To do so you can run the following commands:
Once all files are removed you can proceed to the installation of newer version.
How to setup virtual environment for python3
Virtual environment for python is an isolated space on your computer for Python projects, which allows each of your projects to have its own set of dependencies and don’t disturb any other project. Inside the virtual environment, you can use python and pip commands instead of python3 and pip3 accordingly. Outside of an environment, you must use python3 and pip3 commands for running Python 3.
Following the steps below you can setup a virtual environment for python3 and use it to develop applications.
First of all you need to check if pip (python package manager) installed along with your python installation. If you installed python from source, pip is being installed along with python. To check pip version run:
Output must look like the one below:
If pip isn’t installed on your machine, run the following command to install it:
Once pip is installed you can run the following command to install python packages:
Besides pip you need some more packages that need to be installed as prerequisites. To install them all, run:
Once all prerequisites are installed you can proceed to virtual environment creation. To do so follow the steps below:
Install python3 virtual environment package by running the command below:
Create folder for environments and change your working directory to it. To do so, run:
Create a virtual environment and give it a name which will best describe the environment purpose:
Actually, the command above create a directory with needed files. To view them type:
The output must look like the one below:
To be able to use the newly created environment you must run:
After activating the environment you must see the environment name in brackets in front of your prefix. E.g.
To leave the environment just type the command below:
How to create simple python application within the virtual environment
After virtual environment is created we can create a simple application inside it and test if it works. Our application will output «I am new to Python!» every time we run it. First of all we need to activate the environment or, if you want, enter inside the virtual environment. To do so, change your working directory to environments folder and run the command to activate the desired environment:
Add the following text in the file and save it:
Now every time you run your application with this command:
you’ll see the output:
Python 3 comes already installed with Ubuntu 18.04 and it’s very easy to update it to latest once there is a need. However, if you are using Ubuntu 18’s minimal version you must install python manually and there are two ways to install it. One is using apt, which will install minimal packages of python3 and the other using source code which will install the full version of python 3.
Установка Python 3 в Ubuntu
Установка Python в Ubuntu 20.04
Сначала посмотрите какая версия Python установлена в вашей системе. Для этого выполните команду:
Новая версия, Python 3.9 доступна в репозиториях universe. Поэтому вам нет необходимости добавлять PPA, достаточно просто обновить систему и установить пакет нужной версии. Для этого наберите:
sudo apt update
sudo apt install python3.9
После завершения установки снова можно проверить версию:
Обратите внимание, что старая версия никуда не делась, она по-прежнему доступна по имени python3, а новая теперь может быть загружена командой python 3.9. Если вы хотите использовать эту версию вместо 3.8 для запуска всех программ нужно выбрать её в качестве версии по умолчанию. Но я бы не рекомендовал этого делать. Множество системных программ написаны на Python и протестированы именно с версией, поставляемой по умолчанию. Если вы измените версию что-то может перестать работать. Если вы всё же решились надо сначала добавить альтернативы:
Теперь смотрим ещё раз:
Теперь мы можем выбрать нужную нам версию и переключаться по необходимости. Для настройки используйте команду config:
В запросе ввода нужно указать номер программы, которую следует использовать по умолчанию.
Установка Python 3.10 в Ubuntu
На момент написания статьи Python 3.10 ещё находится в разработке и дата выпуска намечена на октябрь 2021 года. Однако альфа версия уже доступна и вы можете её установить и потестировать если захотите.
sudo add-apt-repository ppa:deadsnakes/ppa
Установка Python 3.10 в Ubuntu 20.04 выполняется командой:
sudo apt install python3.10
Готово, Python установлен и вы можете тестировать его и настраивать версии как описано выше. Для правильно ли прошла установка Python 3 Ubuntu, опять же выполните:
Выводы
В этой статье мы рассмотрели как установить Python на Ubuntu 20.04 и более ранних версий. Рассмотрели как выполняется установка из официальных репозиториев, из PPA и выбор версии. С выбором версии будьте аккуратны, не трогайте python, только python3, как я уже говорил, на Python 2.7 написано множество системных инструментов, и если вы попытаетесь запустить их не той версией интерпретатора, то ничего не получится. Если у вас остались вопросы, спрашивайте в комментариях!
How To Install Python 3 and Set Up a Programming Environment on Ubuntu 20.04 [Quickstart]
Introduction
Python is a flexible and versatile programming language, with strengths in scripting, automation, data analysis, machine learning, and back-end development.
This tutorial will walk you through installing Python and setting up a programming environment on an Ubuntu 20.04 server. For a more detailed version of this tutorial, with more thorough explanations of each step, please refer to How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 20.04 Server.
Step 1 — Update and Upgrade
Logged into your Ubuntu 20.04 server as a sudo non-root user, first update and upgrade your system to ensure that your shipped version of Python 3 is up-to-date.
Confirm installation if prompted to do so.
Step 2 — Check Version of Python
Check which version of Python 3 is installed by typing:
You’ll receive output similar to the following, depending on when you have updated your system.
Step 3 — Install pip
To manage software packages for Python, install pip, a tool that will help you manage libraries or modules to use in your projects.
Python packages can be installed by typing:
Step 4 — Install Additional Tools
There are a few more packages and development tools to install to ensure that we have a robust set-up for our programming environment:
Step 5 — Install venv
Virtual environments enable you to have an isolated space on your server for Python projects. We’ll use venv, part of the standard Python 3 library, which we can install by typing:
Step 6 — Create a Virtual Environment
Step 7 — Activate Virtual Environment
Activate the environment using the command below, where my_env is the name of your programming environment.
Your command prompt will now be prefixed with the name of your environment:
Step 8 — Test Virtual Environment
Open the Python interpreter:
You’ll know you’re in the interpreter when you receive the following output:
Now, use the print() function to create the traditional Hello, World program:
Step 9 — Deactivate Virtual Environment
Quit the Python interpreter:
Then exit the virtual environment:
Further Reading
From here, there is a lot you can learn about Python, here are some links related to this guide:
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 20.04 Server
Introduction
The Python programming language is an increasingly popular choice for both beginners and experienced developers. Flexible and versatile, Python has strengths in scripting, automation, data analysis, machine learning, and back-end development. First published in 1991 with a name inspired by the British comedy group Monty Python, the development team wanted to make Python a language that was fun to use.
This tutorial will get your Ubuntu 20.04 server set up with a Python 3 programming environment. Programming on a server has many advantages and supports collaboration across development projects. The general principles of this tutorial will apply to any distribution of Debian Linux.
Prerequisites
In order to complete this tutorial, you should have a non-root user with sudo privileges on an Ubuntu 20.04 server. To learn how to achieve this setup, follow our initial server setup guide.
If you’re not already familiar with a terminal environment, you may find the article An Introduction to the Linux Terminal useful for becoming better oriented with the terminal.
With your server and user set up, you are ready to begin.
Step 1 — Setting Up Python 3
Ubuntu 20.04 and other versions of Debian Linux ship with Python 3 pre-installed. To make sure that our versions are up-to-date, update your local package index:
Then upgrade the packages installed on your system to ensure you have the latest versions:
Once the process is complete, we can check the version of Python 3 that is installed in the system by typing:
You’ll receive output in the terminal window that will let you know the version number. While this number may vary, the output will be similar to this:
To manage software packages for Python, let’s install pip, a tool that will install and manage programming packages we may want to use in our development projects. You can learn more about modules or packages that you can install with pip by reading How To Import Modules in Python 3.
Python packages can be installed by typing:
There are a few more packages and development tools to install to ensure that we have a robust setup for our programming environment:
Once Python is set up, and pip and other tools are installed, we can set up a virtual environment for our development projects.
Step 2 — Setting Up a Virtual Environment
Virtual environments enable you to have an isolated space on your server for Python projects, ensuring that each of your projects can have its own set of dependencies that won’t disrupt any of your other projects.
Setting up a programming environment provides greater control over Python projects and over how different versions of packages are handled. This is especially important when working with third-party packages.
You can set up as many Python programming environments as you would like. Each environment is basically a directory or folder on your server that has a few scripts in it to make it act as an environment.
While there are a few ways to achieve a programming environment in Python, we’ll be using the venv module here, which is part of the standard Python 3 library. Let’s install venv by typing:
Then navigate to the directory where you’ll store your programming environments:
Once you are in the directory where you would like the environments to live, you can create an environment by running the following command:
Essentially, pyvenv sets up a new directory that contains a few items which we can view with the ls command:
Together, these files work to make sure that your projects are isolated from the broader context of your server, so that system files and project files don’t mix. This is good practice for version control and to ensure that each of your projects has access to the particular packages that it needs. Python Wheels, a built-package format for Python that can speed up your software production by reducing the number of times you need to compile, will be in the Ubuntu 20.04 share directory.
To use this environment, you need to activate it, which you can achieve by typing the following command that calls the activate script:
This prefix lets us know that the environment my_env is currently active, meaning that when we create programs here they will use only this particular environment’s settings and packages.
After following these steps, your virtual environment is ready to use.
Step 3 — Creating a “Hello, World” Program
Now that we have our virtual environment set up, let’s create a traditional “Hello, World!” program. This will let us test our environment and provides us with the opportunity to become more familiar with Python if we aren’t already.
To do this, we’ll open up a command line text editor such as nano and create a new file:
Once the text file opens up in the terminal window we’ll type out our program:
Once you exit out of the editor and return to your shell, you can run the program:
The hello.py program that you created should cause your terminal to produce the following output:
To leave the environment, type the command deactivate and you will return to your original directory.
Conclusion
Congratulations! At this point you have a Python 3 programming environment set up on your Ubuntu Linux server and you can now begin a coding project!
If you are using a local machine rather than a server, refer to the tutorial that is relevant to your operating system in our How To Install and Set Up a Local Programming Environment for Python 3 series.
With your server ready for software development, you can continue to learn more about coding in Python by reading our free How To Code in Python 3 eBook, or consulting our Python tutorials.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
How to Install Python 3 on Ubuntu 18.04 or 20.04
Home » SysAdmin » How to Install Python 3 on Ubuntu 18.04 or 20.04
Python is a popular programming language often used to write scripts for operating systems. It’s versatile enough for use in web development and app design.
In this tutorial you will learn how to install Python 3.8 on Ubuntu 18.04 or Ubuntu 20.04.
Option 1: Install Python 3 Using apt (Easier)
This process uses the apt package manager to install Python. There are fewer steps, but it’s dependent on a third party hosting software updates. You may not see new releases as quickly on a third-party repository.
Most factory versions of Ubuntu 18.04 or Ubuntu 20.04 come with Python pre-installed. Check your version of Python by entering the following:
If the revision level is lower than 3.7.x, or if Python is not installed, continue to the next step.
Step 1: Update and Refresh Repository Lists
Open a terminal window, and enter the following:
Step 2: Install Supporting Software
The software-properties-common package gives you better control over your package manager by letting you add PPA (Personal Package Archive) repositories. Install the supporting software with the command:
Step 3: Add Deadsnakes PPA
Deadsnakes is a PPA with newer releases than the default Ubuntu repositories. Add the PPA by entering the following:
The system will prompt you to press enter to continue. Do so, and allow it to finish. Refresh the package lists again:
Step 4: Install Python 3
Now you can start the installation of Python 3.8 with the command:
Allow the process to complete and verify the Python version was installed sucessfully::
Option 2: Install Python 3.7 From Source Code (Latest Version)
Use this process to download and compile the source code from the developer. It’s a bit more complicated, but the trade-off is accessing a newer release of Python.
Step 1: Update Local Repositories
To update local repositories, use the command:
Step 2: Install Supporting Software
Compiling a package from source code requires additional software.
Enter the following to install the required packages for Python:
Step 3: Download the Latest Version of Python Source Code
To download the newest release of Python Source Code, navigate to the /tmp directory and use the wget command:
Note: The source code is different from the software found on the main download page. At the time this article was written, Python 3.7.5 was the latest version available.
Step 4: Extract Compressed Files
Next, you need to extract the tgz file you downloaded, with the command:
Step 5: Test System and Optimize Python
Before you install the software, make sure you test the system and optimize Python.
The ./configure command evaluates and prepares Python to install on your system. Using the —optimization option speeds code execution by 10-20%.
Enter the following:
This step can take up to 30 minutes to complete.
Step 6: Install a Second Instance of Python (recommended)
To create a second installation of Python 3.835, in addition to your current Python installation, enter the following:
It is recommended that you use the altinstall method. Your Ubuntu system may have software packages dependent on Python 2.x.
(Option) Overwrite Default Python Installation
To install Python 3.8.3 over the top of your existing Python, enter the following:
Allow the process to complete.
Step 7: Verify Python Version
Enter the following:
Note: If you are starting with Python and are still looking for the right IDE or editor, see our comprehensive overview of the best Python IDEs and code editors.
Using Different Versions of Python
If you used the altinstall method, you have two different versions of Python on your system at the same time. Each installation uses a different command.
Use the python command to run commands for any older Python 2.x version on your system. For example:
It is possible to have multiple major (3.x or 2.x) versions of Python on your system. If you have Python 3.7.x and Python 3.8.x both installed, use the second digit to specify which version you want to use:
You should now have a working installation of Python 3 on your Ubuntu system. Next, consider installing PIP for Python if you haven’t already.
With everything set, you can start with some basics scripts like getting the current time and date in Python or learn file handling in Python with built-in methods, which include creating, opening, and closing files.
Источники информации:
- http://losst.ru/ustanovka-python-3-ubuntu
- http://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-programming-environment-on-ubuntu-20-04-quickstart
- http://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-programming-environment-on-an-ubuntu-20-04-server
- http://phoenixnap.com/kb/how-to-install-python-3-ubuntu