How to install yaml

How to install yaml

Библиотека YAML в Python

В этом руководстве мы узнаем, как использовать библиотеку YAML в Python 3. В последние годы она стала очень популярной благодаря использованию для хранения данных в виде сериализованных файлов конфигурации. Поскольку YAML по сути является форматом данных, библиотека YAML довольно простая, поскольку единственная необходимая функциональность – это возможность анализировать файлы в формате YAML.

В этой статье мы начнем с рассмотрения того, как данные хранятся в файле YAML, а затем загрузим эти данные в объект Python. Наконец, мы узнаем, как сохранить объект Python в файле YAML.

Прежде чем мы двинемся дальше, есть несколько предварительных условий для этого урока. Вы должны иметь базовое представление о синтаксисе Python или иметь хотя бы начальный опыт программирования на каком-либо другом языке.

Установка

Процесс установки YAML довольно прост. Это можно сделать двумя способами, начнем с простого.

Метод 1: через точку

Самый простой способ установить библиотеку YAML в Python – через диспетчер пакетов pip. Если в вашей системе установлен pip, выполните следующую команду, чтобы загрузить и установить YAML:

Метод 2: через источник

Если у вас не установлен pip или у вас возникли проблемы с описанным выше методом, вы можете перейти на исходную страницу библиотеки. Загрузите репозиторий в виде zip-файла, откройте терминал или командную строку и перейдите в каталог, в который загружен файл. Когда вы окажетесь там, выполните следующую команду:

Примеры кода

В этом разделе мы узнаем, как обрабатывать (манипулировать) файлами YAML, начиная с того, как их читать, то есть как загружать их в наш скрипт Python, чтобы мы могли использовать их в соответствии с нашими потребностями.

Чтение файлов

В этом разделе мы увидим, как читать файлы YAML в Python. Начнем с создания двух файлов в формате YAML.

Содержимое первого файла выглядит следующим образом:

Содержимое второго файла выглядит следующим образом:

Вы можете видеть, что файлы fruit.yaml и category.yaml содержат разные типы данных. Первый содержит информацию только об одном объекте, то есть о фруктах, а второй содержит информацию о видах спорта и странах.

Давайте теперь попробуем прочитать данные из двух файлов, которые мы создали с помощью скрипта Python. Метод load() из модуля yaml можно использовать для чтения файлов YAML. Взгляните на следующий скрипт:

В приведенном выше скрипте мы указали yaml.FullLoader в качестве значения для параметра Loader, который загружает полный язык YAML, избегая выполнения произвольного кода. Вместо использования функции загрузки и последующей передачи yaml.FullLoader в качестве значения параметра Loader вы также можете использовать функцию full_load(), как мы увидим в следующем примере.

Давайте теперь попробуем прочитать второй файл YAML аналогичным образом, используя скрипт Python:

Поскольку в файле category.yaml 2 документа, мы выполнили цикл, чтобы прочитать их оба.

Как видно из последних двух примеров, библиотека автоматически обрабатывает преобразование данных в формате YAML в словари и списки Python.

Запись

Теперь, когда мы узнали, как преобразовать файл YAML в словарь Python, давайте попробуем сделать что-то наоборот, то есть сериализовать словарь Python и сохранить его в файл в формате YAML. Для этого воспользуемся тем же словарем, который мы получили в результате нашей последней программы.

Метод dump() принимает словарь Python как первый, а объект File как второй параметр.

После выполнения приведенного выше кода в вашем текущем рабочем каталоге будет создан файл с именем store_file.yaml.

Еще одна полезная функция, которую предлагает библиотека YAML для метода dump(), – это параметр sort_keys. Чтобы показать, что он делает, применим его к нашему первому файлу, то есть fruit.yaml:

В выводе видно, что фрукты отсортированы в алфавитном порядке.

Заключение

В этом кратком руководстве мы узнали, как установить библиотеку Python YAML (pyyaml) для управления файлами в формате YAML. Мы рассмотрели загрузку содержимого файла YAML в нашу программу Python в виде словарей, а также сериализацию словарей и сохранение их ключей. Библиотека довольно краткая и предлагает только основные функции.

How do I install the yaml package for Python?

I have a Python program that uses YAML. I attempted to install it on a new server using pip install yaml and it returns the following:

How do I install the yaml package for Python? I’m running Python 2.7. (OS: Debian Wheezy)

12 Answers 12

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You could try the search feature in pip,

which looks for packages in PyPI with yaml in the short description. That reveals various packages, including PyYaml, yamltools, and PySyck, among others (Note that PySyck docs recommend using PyYaml, since syck is out of date). Now you know a specific package name, you can install it:

If you want to install python yaml system-wide in linux, you can also use a package manager, like aptitude or yum :

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

pip install pyyaml

This answers if for MacOS

Update: Nowadays installing is done with pip, and for many users a wheel may be available (depending on your Mac and required version of PyYaml). In some cases libyaml is still required to build the C extension (on mac); this can be done with:

For MacOSX (mavericks), the following works:

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

If libyaml is not found or compiled PyYAML can do without it on Mavericks.

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

There are three YAML capable packages. Syck ( pip install syck ) which implements the YAML 1.0 specification from 2002; PyYAML ( pip install pyyaml ) which follows the YAML 1.1 specification from 2004; and ruamel.yaml which follows the latest (YAML 1.2, from 2009) specification.

You can install the YAML 1.2 compatible package with pip install ruamel.yaml or if you are running a modern version of Debian/Ubuntu (or derivative) with:

$ sudo aptitude install python-yaml

or newer for python3

$ sudo aptitude install python3-yaml

Install the libYAML and it’s headers:

Download the pyyaml sources:

Install from sources, (don’t forget to activate your venv):

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Consider using strictyaml instead

If you have the luxury of creating the yaml file yourself, or if you don’t require any of these features of regular yaml, I recommend using strictyaml instead of the standard pyyaml package.

In short, default yaml has some serious flaws in terms of security, interface, and predictability. strictyaml is a subset of the yaml spec that does not have those issues (and is better documented).

OPINION: strictyaml should be the default implementation of yaml and the old yaml spec should be obsoleted.

How to Install python-YAML package on Linux?

PyYAML is a special Python library for the package that is often used for the configuration of files and also can be used for data exchange purposes. PyYAML package is a Python YAML parser that permits the user to write YAML data and also parse it. PyYAML library is quite similar to the JSON library in Python which allows the user to work with JSON formatted data. So, In this article, we will be installing the PyYAML Python library on Linux System.

Installing the PyYAML package on Linux using PIP

Requirements:

To install the PyYAML package in Linux follow the following steps:

Step 1: Firstly, we will install the current version of Python3 using the following command.

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Step 2: Now, we will install the pip package manager, which is responsible for installing the external packages. Use the below command to install the pip manager

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Step 3: Now using the PIP manager we are going to install the PyYAML package. So for the installation run the following command on the terminal.

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Verifying the installation of the PyYAML package

After installing the package, the next important step is to check the installation of the PyYAML package is successful or not. So here, we are simply getting the information of the installed package (PyYAML) by executing the below command on the terminal itself.

The below output will be displayed after the successful installation of the PyYAML package on your Linux machine.

How to Install the PHP YAML Extension

The PHP YAML extension provides PHP functions for parsing and serializing files and text containing YAML markup.

Installing the YAML Extension on PHP 7.3

This extension does not yet support PHP 7.3.

Installing the YAML Extension on PHP 7.0, 7.1, and 7.2

To install the PHP YAML extension on PHP 7.0, PHP 7.1, or PHP 7.2, SSH in to your server as root and first run these commands:

Next, run the following command:

When you receive this prompt:

press Enter without entering a prefix. This allows the library’s location to be autodetected.

Once installed, create a configuration file for the extension and restart PHP by running the following command as root:

Installing the YAML Extension on PHP 5.X

To install this extension on PHP 5.4, 5.5, or 5.6, first run the following commands as your server’s root user:

Next, run the following command:

When you receive this prompt:

press Enter without entering a prefix. This allows the library’s location to be autodetected.

Once installed, create a configuration file for the extension and restart PHP by running the following command as root:

Verifying the PHP YAML Extension Is Installed

You can verify the YAML extension is installed by running this command, where X.Y is your app’s PHP version:

You should see output similar to the following:

Uninstalling the YAML Extension

To uninstall this extension, as root run the commands:

How to Install YAML and Use in PHP

YAML is a human-readable data-serialization mark-up language. It is better than another mark-up language, XML to store the data because YAML content is easy to read and write. YAML syntax rules are used to create a YAML file that is a text file with the extension “.yml“. Many built-in functions exist in PHP for the YAML package. How YAML can be installed and used in PHP have shown in this tutorial.

Install YAML:

YAML extension is not installed and enables in PHP by default. So, you have to install the YAML package of PHP before trying the script in this tutorial.

Update the operating system by running the following command.

Install the yaml package of PHP by running the following command.

Restart the apache server to make the yaml extension enabled for PHP.

Convert any data into YAML content:

yaml_emit() function is used to convert any data into YAML content. The syntax of this function is shown below.

Syntax:

This function returns the YAML representation of any data. It can take four argument values. The first argument is mandatory and can any type of data. The other three arguments are optional. YAML has different types of encoding to generate output. The first optional argument can take any of YAML encoding as the argument value. YAML has different types of line break options also. The second optional argument can take any of the YAML line breaks. The third optional argument can take any call back function that returns an array.

Another function named yaml_emit_file() exists in the YAML package to store the YAML content into a file after converting the data. This function is supported only for YAML version 0.5.0 or more.

Example-1: Use of yaml_emit() function

The following example shows how the yaml_emit() function can be used to convert a two-dimensional associative array into YAML content. Create a PHP file with the following script. A two-dimensional array named $employees is declared in this script that contains five rows and four columns. tag is used to print YAML content in a structured format.

//Define a two-dimensional array

//Convert the array into YAML content

//Print the array

Output:

The following output will appear after running the script from the server. The output shows that the YAML content starts with ‘‘ and ends with ‘‘. Each row is identified by the employee ID that is printed first and the column values are printed under each employee ID.

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Convert YAML content into an array:

yaml_parse() function is used to convert YAML content into an array. The syntax of this function is given below.

Syntax:

This function can take four arguments and returns mixed data. The first argument is mandatory that will take YAML content as the argument value. The other three arguments are optional. The first optional argument is used to extract the document from the stream. The second optional argument is used to set the number of documents in the stream. The third optional document is used for defining the callback function.

Example-2: Use of yaml_parse() function

The following example shows how the yaml_parse() function can be used to convert any YAML content into an array. Create a PHP file with the following script. The YAML content is stored in the variable $yaml here. A delimiter is used to define the YAML content. The content starts with the delimiter followed by the ‘ ?php

// Define YAML content into a variable

// Convert the YAML content into an array and print

Output:

The following output will appear after running the script from the server. According to the YAML content, the following array will be generated. The output shows that the Sales department contains three employee information and the HR department contains two employee information.

How to install yaml. Смотреть фото How to install yaml. Смотреть картинку How to install yaml. Картинка про How to install yaml. Фото How to install yaml

Conclusion:

YAML is a useful package of PHP for storing data or transferring data from one format to another format. YAML package contains many functions to store data or read data from different formats. The uses of yaml_emit() and yaml_parse() functions are explained in this tutorial by using two examples. I, hope, the concept of using the YAML package in PHP will be cleared for the readers after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *