Configparser for python 3

configparser 6.0.0

Updated configparser from stdlib for earlier Pythons.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License

Сопровождающий: Jason R. Coombs

Метки configparser, ini, parsing, conf, cfg, configuration, file

Требует: Python >=3.8

Сопровождающие

Классификаторы

Описание проекта

This package is a backport of the refreshed and enhanced ConfigParser from later Python versions. To use the backport instead of the built-in version, simply import it explicitly as a backport:

from backports import configparser

To use the backport on Python 2 and the built-in version on Python 3, use the standard invocation:

For detailed documentation consult the vanilla version at http://docs.python.org/3/library/configparser.html.

Why you’ll love configparser

Whereas almost completely compatible with its older brother, configparser sports a bunch of interesting new features:

    full mapping protocol access (more info):

>>> parser = ConfigParser() >>> parser.read_string(""" [DEFAULT] location = upper left visible = yes editable = no color = blue [main] title = Main Menu color = green [options] title = Options """) >>> parser['main']['color'] 'green' >>> parser['main']['editable'] 'no' >>> section = parser['options'] >>> section['title'] 'Options' >>> section['title'] = 'Options (editable: %(editable)s)' >>> section['title'] 'Options (editable: no)'
  • the classic %(string-like)s syntax (called BasicInterpolation )
  • a new $ syntax (called ExtendedInterpolation )
>>> config.get('closet', 'monster', . fallback='No such things as monsters') 'No such things as monsters'

A few words about Unicode

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files. There are a couple of incompatibilities with the old ConfigParser due to that. However, the work required to migrate is well worth it as it shows the issues that would likely come up during migration of your project to Python 3.

The design assumes that Unicode strings are used whenever possible [ 1 ] . That gives you the certainty that what’s stored in a configuration object is text. Once your configuration is read, the rest of your application doesn’t have to deal with encoding issues. All you have is text [ 2 ] . The only two phases when you should explicitly state encoding is when you either read from an external source (e.g. a file) or write back.

Читайте также:  Objects meaning in java

Versioning

This project uses semver to communicate the impact of various releases while periodically syncing with the upstream implementation in CPython. The history serves as a reference indicating which versions incorporate which upstream functionality.

Prior to the 4.0.0 release, another scheme was used to associate the CPython and backports releases.

Maintenance

This backport was originally authored by Łukasz Langa, the current vanilla configparser maintainer for CPython and is currently maintained by Jason R. Coombs:

Conversion Process

This section is technical and should bother you only if you are wondering how this backport is produced. If the implementation details of this backport are not important for you, feel free to ignore the following content.

The project takes the following branching approach:

  • The 3.x branch holds unchanged files synchronized from the upstream CPython repository. The synchronization is currently done by manually copying the required files and stating from which CPython changeset they come.
  • The main branch holds a version of the 3.x code with some tweaks that make it compatible with older Pythons. Code on this branch must work on all supported Python versions. Test with tox or in CI.

The process works like this:

  1. In the 3.x branch, run pip-run — sync-upstream.py , which downloads the latest stable release of Python and copies the relevant files from there into their new locations and then commits those changes with a nice reference to the relevant upstream commit hash.
  2. Check for new names in __all__ and update imports in configparser.py accordingly. Commit.
  3. Merge the new commit to main . Run tests. Commit.
  4. Make any compatibility changes on main . Run tests. Commit.
  5. Update the docs and release the new version.

Footnotes

To somewhat ease migration, passing bytestrings is still supported but they are converted to Unicode for internal storage anyway. This means that for the vast majority of strings used in configuration files, it won’t matter if you pass them as bytestrings or Unicode. However, if you pass a bytestring that cannot be converted to Unicode using the naive ASCII codec, a UnicodeDecodeError will be raised. This is purposeful and helps you manage proper encoding for all content you store in memory, read from various sources and write back.

Life gets much easier when you understand that you basically manage text in your application. You don’t care about bytes but about letters. In that regard the concept of content encoding is meaningless. The only time when you deal with raw bytes is when you write the data to a file. Then you have to specify how your text should be encoded. On the other end, to get meaningful text from a file, the application reading it has to know which encoding was used during its creation. But once the bytes are read and properly decoded, all you have is text. This is especially powerful when you start interacting with multiple data sources. Even if each of them uses a different encoding, inside your application data is held in abstract text form. You can program your business logic without worrying about which data came from which source. You can freely exchange the data you store between sources. Only reading/writing files requires encoding your text to bytes.

Читайте также:  Creating function in javascript

For Enterprise

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

Источник

ConfigParser в Python — как его использовать?

Файлы конфигурации используются как пользователями, так и программистами. Как правило, их используют для хранения настроек вашего приложения, или операционной системы. Библиотека в ядре Python включает в себя модуль, под названием configparser, который вы можете использовать для создания и работы с файлами конфигурации. Что ж, давайте выделим несколько минут на то, чтобы узнать, как это работает.

Совместимость с Python 3

Из за нововведений в стандарте PEP 8 модуль ConfigParser в Python 3 был переименован в configparser. Возможные ошибки:
ImportError: no module named ConfigParser

Решение проблемы совместимости

Создание файла

Создание файла config при помощи configparser невероятно просто. Давайте напишем небольшой код, чтобы посмотреть, как это работает:

Данный код создает файл config с одной секцией, под названием Settings, которая будет содержать наши опции: font, font_size, font_style и font_info. Обратите внимание на то, что в Python 3 нам нужно указать, что мы пишем файл в режиме write-only, или “w”. А в Python 2.7, мы использовали “wb” для написания в бинарном режиме.

Как читать, обновлять и удалять опции

Теперь мы готовы к тому, что бы научиться чтению файла config, обновлять его опции и даже удалять их. В нашем случае учиться будет намного проще, если мы попробуем на практике написать какой-нибудь код. Просто добавьте следующую функцию в код, который вы писали ранее.

Читайте также:  Html link to header on page

Этот код сначала проверяет, существует ли файл config в принципе. Если его нет, то он использует созданную нами ранее функцию createConfig, чтобы создать файл. Далее мы создаем объект ConfigParser и указываем путь к файлу config для чтения. Чтобы прочесть опцию в вашем config файле, мы вызываем метод нашего объекта ConfigParser, указываем ему наименование секции и опции.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Это вернет значение параметра. Если вы хотите изменить значение опции, вам нужно использовать метод set, в котором вы указываете название секции, опции, и новое значение. Наконец, мы можем использовать метод remove_option, чтобы удалить опцию. В нашем примере мы изменили значение font_size, и задали ему размер 12, затем мы удалили опцию font_style. После этого мы записали наши изменения на диск. Этот пример на на столько хорош, давайте упростим наш код. Для этого мы разделим наш код на на несколько функции:

Этот пример выглядит более организованно, по сравнению с первым. Я зашел так далеко, что назвал функции соответственно стандартам PEP8. Каждая функция должна объяснять сама себя и выполнять лишь одну задачу. Вместо того, чтобы помещать всю логику в одну единственную функцию, мы разделяем её на несколько функций, после чего демонстрируем их функционал в конце оператора if. Теперь вы можете импортировать модуль и использовать по назначению. Обратите внимание на то, что в этом примере есть сложная секция, так что вам, возможно, захочется усовершенствовать этот пример в дальнейшем, чтобы сделать его более универсальным.

Как использовать интерполяцию

Модуль configparser также подразумевает возможность интерполяции, что значит, что вы можете использовать существующие опции, для создания другой опции. Мы на самом деле это делали с опцией font_info, чьи параметры основаны на опциях font и font_size. Мы можем изменить интерполированное значение при помощи словаря Python. Давайте уделим несколько минут, и взглянем на оба случая.

Источник

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