Install python linux terminal

How do I install python through the terminal?

Can you add more info as to what you have done — with which command did you download it, try to run it, etc.?

3 Answers 3

Python is installed to all of our computers because it is useful framework for a variety of things .

To use the python interface from terminal just type python .

to check you python version just type python —version

to run a python script you need to type in the form :

but very importantly it has to be executable first

chmod +x python_script_name.py

sudo apt-get install python 

It will show you whether you have newest version of python or you should upgrade

How do I install python through the terminal?

Python comes preinstalled on ubuntu in all recent releases. You can just type python in the terminal to access python 2 or python3 to access python3.

I downloaded python through the terminal, but when I went to run it, all I got was a whole bunch of script. Any suggestions? I am using lubuntu

It is unclear how you downloaded it. Normally you would simply run

sudo apt-get install python sudo apt-get install python3 

These really are the ways to install python in Ubuntu. Don’t start downloading stuff yourself. It will mess up your system because Ubuntu also uses python a lot for the OS itself. There are some expert ways to install python, but they might be too advanced for you.

Источник

How to Install Python on Linux?

Python Certification Course: Master the essentials

In this article, you will learn all about starting your journey with this Python tutorial by installing and interacting with Python for Linux. Follow the steps and start coding in no time!

Introduction

Rahul recently read an article on «what is Python?» and came across all the amazing things he can create and achieve using Python. Rahul is highly intrigued and wishes to start his Python journey immediately. This is no surprise, as Python is a widely-used, high-level programming language used across various disciplines.

Well, if this sounds anything like you, then you are at the right place! The first step to becoming a Pythoneer or a Pythonista, if you are a Linux user, is to know the answer to the question “How to Install Python on Linux and interact with it?”

Prerequisite to Install Python on Linux

You will need certain prerequisites to be met before you successfully know how to install Python on Linux. They are as follows-

  • A computer running on Debian / Fedora OS with a minimum of 2GB RAM (4GB Preferable) and 5GB of disk space
  • Also, you need sudo access on the system you want to install Python on Linux
Читайте также:  Kernel testing in linux

sudo command: It allows you to temporarily elevate your current user account to have root privileges.

How to Check the Python Version on Linux?

Python comes preinstalled on most of the Linux distributions like Debian.

You can simply check the Python Version, which is already installed on your system, by running python -V or python —version command on your terminal.

Check Python Version on Linux

When Python is not already installed: The output will be something like this-

When Python is already Installed: The output will be something like this-

Python is already installed

Python x.x.x For example, Python 3.8.5-

Two Ways to Install Python on Linux

I. Install Python on Linux from Package Manager:

The following command could be used to install the latest version of Python on almost every Linux system.

Also, you can mention the particular version of Python you want to install, shown below :

Install Python on Linux from Package Manager

Type Y and press Enter to continue. The Package manager will download and install the Python for you.

Download Python from Package Manager

II. Build from source code

Before starting, please make sure that you have git , gcc , and make installed on your system.

Steps to be followed to Build Python from Source Code:

1. Get the Source code:

We can clone the latest Python source code from Python’s official GitHub repository using git to install Python on Linux.

Get Source Code in Python

2. Configure:

The configuration script comes with the source code that can be passed through many flags.

  • —prefix : Used to determine where the final built files go
  • —enable-optimizations — Enable Profile Guided Optimization (PGO) using PROFILE_TASK (disabled by default). Optimization takes a long time to configure, but the resulting python binary interpreter is 10% faster at executing Python code.
  • Navigate to the cpython directory where we have cloned Python source code-

Note: $HOME will contain the path to the current user’s home directory. You can check your home directory by using the echo command.

Add Command in Python

Your terminal will show something like this once the configuration is done —

Terminal in Python

  • Once the configuration is done, we are ready to start the build process.
  • Run the make tool to build the files, followed by the make install command to put the built files in the location specified by configure’s —prefix .
  • The final output of the make command will be something like this —

Build Command in Python

Output of Make Install in Python

Step by Step Guide to Install Python on Linux

  • Step 1 — Install Development Packages Required to Install Python on Linux-
    1. On Debian
    2. On Fedora
  • Step 2 — Download the Latest Version of Python
  • Step 3 — Extract the tar file to install Python on Linux
  • Step 4 — Configure the Script
  • Step 5 — Getting Through the steps to install Python on Linux and finishing installation
  • Step 6 — Verify the Installation
  • Step 7 — Create Virtual Environment(Optional)

1. Install Development Packages Required to install Python on Linux:

On Debian: Follow the below steps to install the development packages required to install Python on Linux (Debian system)-

    Ensure you have enabled the source packages in the sources list. You can do this by adding the location of the source packages, including URL, distribution name, and component name, to /etc/apt/sources.list . Take Ubuntu Bionic, for example:

Update Package Index in Python

Install the Python Build dependencies: You can install the build dependencies by running the below command on your Terminal.

Step 2- Download latest version of Python:

You can download the latest version of Python as tar file by visiting python.org.

Download latest version of python

Just click on the download button to download the tar file. Note: At the time of writing this article, the latest version of Python was 3.9.6.

Step 3- Extract the tar file to install Python on Linux:

Once the download is completed, open the Terminal and navigate to the Downloads directory.

Run the below tar command to extract the files-

Extract tar file in Python

In our case the name of the downloaded file is Python-3.9.6.tar.xz . So the command will be-

The above command will create a directory in the name of the file (without file extension). So the name of the directory will be Python-3.9.6 .

Step4- Configuring the Script:

Configuring script in python

Follow the Configure and Build steps of Build from source code.

Let’s create an alias for Python 3.9 so the version will not confuse us. An alias can be easily created by using alias commands like those given below.

Step 5- Getting Through the steps to install Python on Linux and finishing installation

In this step, you have to let the system do its thing and wait for it to install Python on Linux.

Step 6- Verify the installation:

You are so close to completing the installation of Python on Linux! Now, open any of your favorite code/text editors and add the below code.

Verify Installation in Python

Save the file with the .py extension. For example, helloworld.py .

Save File in Python

Open terminal inside the directory where you saved the .py file. And run the program file using the python command.

Output of python program

The output of the program-

Step 7- Create Virtual Environment(Optional) :

There are many ways to create a Python virtual environment after you have learnt how to install Python on Linux. Here we are going to see how to create a python virtual environment using the virtual environment package which comes with Python3.

You can create a Python virtual environment by just running the below command on your Terminal.

Create virtual environment

Replace test_env with the path where you want to store your virtual environment

Then verify the created virtual environment by using the ls command shown in the above picture.

You may get the output as shown in the picture below if the Python virtual environment is not installed already.

Verify python virtual environment

In this case, you can install the package by using the below command-

Install python 3 package

Press Y and Enter to continue the installation.

Continue Installation in Python

Now again, try to run the command to create the virtual environment.

The newly created virtual environment can be activated by using the source command-

Activate virtual environment

Here also replace the test_env with your virtual environment path.

Conclusion

  • You can now finally say you know how to install Python on Linux!
  • After reading this article, you should be able to Configure, Install and Run Python on a Linux system and be able to create a Python virtual environment.
  • Important things to remember while you install Python on Linux-
  • Be sure always to check the version you are installing and its compatibility with the Operating System installed on your system.
  • After setup is done, always verify if Python is successfully installed.

Read More:

Источник

Установка Python 3 в Ubuntu

Python — это один из самых популярных языков программирования для Linux. На нем написано множество различных инструментов и библиотек. Кроме того, Python популярен среди разработчиков, потому что на нем очень просто и быстро программировать, и вообще, его просто освоить.

По умолчанию в Ubuntu уже поставляется интерпретатор Python, но сейчас в официальных репозиториях доступна только версия 3.5 и версия 2.7 для совместимости со старыми скриптами. Но самая новая версия на данный момент — 3.8. Однако уже доступны и более новые версии. В этой статье мы рассмотрим как установить Python 3 в Ubuntu 20.04.

Установка 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 и протестированы именно с версией, поставляемой по умолчанию. Если вы измените версию что-то может перестать работать. Если вы всё же решились надо сначала добавить альтернативы:

sudo update-alternatives —install /usr/bin/python3 python3 /usr/bin/python3.8 1
sudo update-alternatives —install /usr/bin/python3 python3 /usr/bin/python3.9 2

update-alternatives —list python3

Теперь мы можем выбрать нужную нам версию и переключаться по необходимости. Для настройки используйте команду config:

sudo update-alternatives —config python3

В запросе ввода нужно указать номер программы, которую следует использовать по умолчанию.

Установка 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 написано множество системных инструментов, и если вы попытаетесь запустить их не той версией интерпретатора, то ничего не получится. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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