- Python in Linux
- Contents
- Introduction
- Python Setup
- While Building a Linux Image
- Using existing packages
- Writing your own recipes
- Before writing the recipe
- Writing the recipe
- Performance & Suitability
- Examples
- GPIO — Blinking LED
- RTC — Read Time
- Как установить Python 3.8 на Ubuntu, Debian и LinuxMint
- Подготовка к установке Python 3.8 на Ubuntu, Debian и LinuxMint
- Ошибка ImportError: No named ‘_tkinter’
- Скачать Python 3.8 для Ubuntu, Debian и LinuxMint
- Компиляция исходного кода Python для Ubuntu, Debian и LinuxMint
- Проверка версии Python на системах Ubuntu, Debian и LinuxMint
- 2. Using Python on Unix platforms¶
- 2.1. Getting and installing the latest version of Python¶
- 2.1.1. On Linux¶
- 2.1.2. On FreeBSD and OpenBSD¶
- 2.1.3. On OpenSolaris¶
- 2.2. Building Python¶
- 2.3. Python-related paths and files¶
- 2.4. Miscellaneous¶
- 2.5. Custom OpenSSL¶
- Installing Python 3 on Linux¶
- Working with Python 3¶
- Setuptools & Pip¶
- Pipenv & Virtual Environments¶
- O’Reilly Book
Python in Linux
Contents
Introduction
Python is a widely used interpreted language. Despite the performance gap when compared to a compiled solution, it is still suitable for some applications.
This article focuses on the BSP Layers and Reference Images for Yocto Project. If you want to learn how to use Python on Torizon, read the article Python development on TorizonCore.
Python Setup
While Building a Linux Image
A set of python packages can be added to an OpenEmbedded Linux build for inclusion into the image’s root file system. After establishing the image build configuration, additionally append the following line to the oe-core/build/conf/local.conf file:
You may also want to install other packages as python-pip and dependencies to the Python packages you plan to use.
Using existing packages
You can search related Python packages using the OpenEmbedded recipes index or by searching the layers directory of your build environment. An example is provided to search for the pyserial package:
Writing your own recipes
Even if you are starting with OpenEmbedded, writing recipes for Python modules is usually straightforward. There are many recipes out there that do it for you to use as examples and their structure looks very alike.
A possible path for writing a recipe is provided below. We use the TinyDB 3.7.0 release for illustration:
Before writing the recipe
- Go to the Python Package Index and find the package you are after. In our example TinyDB.
- Find the downloads section, copy the download link and download the package to your PC. In our case, tinydb downloads section.
- Find the license type. In our case is MIT.
- Generate the md5 and sha256 checksums for the compressed package. In our case md5:e28a5650ef8796ab6b7892591edfbae8 and sha256:071105c339b44f928968cb4e62f7340a568beb9962a3dcda66eb82da9cab0b0a
- Unpack the compressed package and search for the license file — common namings are README or LICENSE, but it may be a different name. In our example the name of the license file is PKG-INFO.
- Generate the md5sum for the license file. For the .tar.gz compressed release of TinyDB 3.7.0, it is 8e3a385933697d0374af36db8ee0319d.
- Try to understand which are the package dependencies. You can do this empirically once you have written the recipe.
Writing the recipe
We will create three files:
Note: Follow the dash, underscore and case standard provided, since those matter for OpenEmbedded. See the project documentation for further details.
- package-name.inc: this is common information to be used in Python 2 and Python 3 recipes.
- python-package-name_version.bb: recipe to build Python 2 module.
- python3-package-name_version.bb: recipe to build Python 3 module.
For our example:
- python-tinydb.inc
- python-tinydb_3.7.0.bb
- python3-tinydb_3.7.0.bb
First create a new layer (recommended) to hold all your OpenEmbedded customizations, or you can do it in an existing layer also for studying purposes.
Create the files provided below:
Now you can add the package to your image, e.g. for TinyDB:
Performance & Suitability
Tests results are pending; however, Python is expected to perform at least an order of magnitude slower than equivalent compiled C/C++ code due to Python’s run-time interpreted nature. Use of a Just-in-Time or Ahead-of-Time compiler should improve performance; however, such compilers have not been tested with our Linux images.
Regardless, Python is still a viable alternative for performing lighter processing tasks. It can be effective for low level IO operations as well as high level applications such as web services. Furthermore, Python code can be rapidly modified and tested without the need to recompile.
Examples
GPIO — Blinking LED
Blinking a LED using GPIO access through sysfs.
RTC — Read Time
Note: The modules fcntl and glob are provided by the packages ‘python-fcntl’ and ‘python-shell’ respectively.
Источник
Как установить Python 3.8 на Ubuntu, Debian и LinuxMint
Совсем недавно стала доступна новая версия Python — Python 3.8. Теперь она доступна для скачивания и последующей установки каждому пользователю. В следующем руководстве будет показано, как установить Python 3.8 на операционные системы Ubuntu, Debian и LinuxMint. Подробнее о релизах Python можно узнать здесь.
Подготовка к установке Python 3.8 на Ubuntu, Debian и LinuxMint
Python 3.8 будет устанавливаться из исходника. По этой причине изначально требуется установить несколько библиотек разработки для компиляции исходного кода Python. Для установки всех необходимых компонентов для Python используется следующая команда:
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
Ошибка ImportError: No named ‘_tkinter’
Данная ошибка появляется из за того, что Tkinter не был установлен ДО компиляции Python. Сперва вам нужно установить Tkinter потом уже собрать нужную версию Python. Иначе, после установки Python вы никак не сможете устранить эту ошибку.
Скачать Python 3.8 для Ubuntu, Debian и LinuxMint
Скачайте исходный код Python 3.8 с официального сайта, используя следующую команду. Также можно скачать последнюю версию по точной ссылке, указанной ниже.
Распакуйте файл исходного кода из архива:
Компиляция исходного кода Python для Ubuntu, Debian и LinuxMint
Для компиляции исходного кода Python на систему Linux используйте указанный ниже набор команд, используя altinstall .
make altinstall используется для предотвращения замены бинарного файла Python, который по умолчанию в /usr/bin/python .
Проверка версии Python на системах Ubuntu, Debian и LinuxMint
Проверить текущую версию Python можно при помощи следующей команды. Версия в системе по умолчанию переписана не была, поэтому используем команду для Python 3.8, что следующая:
После успешной установки для экономии места на диске можете удалить загруженный архив при помощи следующей команды:
Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.
E-mail: vasile.buldumac@ati.utm.md
Образование
Universitatea Tehnică a Moldovei (utm.md)
- 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
- 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»
Источник
2. Using Python on Unix platforms¶
2.1. Getting and installing the latest version of Python¶
2.1.1. On Linux¶
Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.
In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:
for Debian users
for OpenSuse users
for Fedora users
for Slackware users
2.1.2. On FreeBSD and OpenBSD¶
FreeBSD users, to add the package use:
OpenBSD users, to add the package use:
For example i386 users get the 2.5.1 version of Python using:
2.1.3. On OpenSolaris¶
You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .
2.2. Building Python¶
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)
The build process consists of the usual commands:
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .
2.3. Python-related paths and files¶
These are subject to difference depending on local installation conventions; prefix ( $
For example, on most Linux systems, the default for both is /usr .
Recommended location of the interpreter.
prefix /lib/python version , exec_prefix /lib/python version
Recommended locations of the directories containing the standard modules.
prefix /include/python version , exec_prefix /include/python version
Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.
2.4. Miscellaneous¶
To easily use Python scripts on Unix, you need to make them executable, e.g. with
and put an appropriate Shebang line at the top of the script. A good choice is usually
which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2.5. Custom OpenSSL¶
To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.
Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .
Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
Источник
Installing Python 3 on Linux¶
This document describes how to install Python 3.6 or 3.8 on Ubuntu Linux machines.
To see which version of Python 3 you have installed, open a command prompt and run
If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:
If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a more current Python, we recommend using the deadsnakes PPA to install Python 3.8:
If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution’s package manager. For example on Fedora, you would use dnf :
Note that if the version of the python3 package is not recent enough for you, there may be ways of installing more recent versions as well, depending on you distribution. For example installing the python3.9 package on Fedora 32 to get Python 3.9. If you are a Fedora user, you might want to read about multiple Python versions available in Fedora.
Working with Python 3¶
At this point, you may have system Python 2.7 available as well.
This might launch the Python 2 interpreter.
This will always launch the Python 3 interpreter.
Setuptools & Pip¶
The two most crucial third-party Python packages are setuptools and pip.
Once installed, you can download, install and uninstall any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.
Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default.
To see if pip is installed, open a command prompt and run
To install pip, follow the official pip installation guide — this will automatically install the latest version of setuptools.
Note that on some Linux distributions including Ubuntu and Fedora the pip command is meant for Python 2, while the pip3 command is meant for Python 3.
However, when using virtual environments (described below), you don’t need to care about that.
Pipenv & Virtual Environments¶
The next step is to install Pipenv, so you can install dependencies and manage virtual environments.
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.
This page is a remixed version of another guide, which is available under the same license.
This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
O’Reilly Book
This guide is now available in tangible book form!
All proceeds are being directly donated to the DjangoGirls organization.
Источник