Переместить раздел из одного файла конфигурации в другой с помощью configparser - PullRequest
0 голосов
/ 08 марта 2019

У меня есть два файла:

test1.conf:

[1414]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

test2.conf:

[1415]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

Я просто хочу поместить раздел [1414] из test1.conf в раздел из test2.conf, а затем удалить из test1.conf

Я попытался преобразовать раздел в словарь и затем добавить его в test2, но он не включал в себя имя раздела, только конфиги, и мне нужно переместить все конфиги (имя раздела и его конфиги).

Мне просто нужно с чем-то поработать, тогда я посмотрю, что я могу сделать, чтобы вставить это в мой код. Конечно, я прочитал документацию, но не смог найти ничего, что могло бы вставить полный раздел.

Вот что я попробовал (файл большой, поэтому я его получил):

config = configparser.ConfigParser(strict=False,comment_prefixes='/',allow_no_value=True)
with open('test1.conf', "r") as f:
    config.readfp(f)

for general_queue_id in config.sections():
    general_id_arr.append(general_queue_id)

for key in general_id_arr: # Array with all sections from test1.conf
    with open('teste2.conf'):
        items = {k:v for k,v in config.items(key)}
        for x in items.items():
            f.write(x[0] + '=' + x[1] + '\n')

1 Ответ

0 голосов
/ 19 апреля 2019

Если вы уже знаете, какой раздел вы ищете, вам будет проще использовать встроенные функции из configParser, которые вы можете встроить в класс-оболочку.

Например, я использую следующее для создания моего парсера, а затем собираю все элементы в разделе в виде списка.

from configparser import ConfigParser, ExtendedInterpolation


class MyConfigParser(object):

    def __init__(self):
        """
        initialize the file parser with
        ExtendedInterpolation to use ${Section:variable} format
        [Section]
        option=variable
        """
        self.config_parser = ConfigParser(interpolation=ExtendedInterpolation())

    def read_ini_file(self, file):
        """
        Parses in the passed in INI file.

        :param file: INI file to parse
        :return: INI file is parsed
        """
        with open(file, 'r') as f:
            self.config_parser.read_file(f)

    def add_section_toFile(self, section):
        """
        adds a configuration section to a file

        :param section: configuration section to add in file
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.config_parser.add_section(section)

    def add_configurations_to_section(self, section, lst_config):
        """
        Adds a configuration list to configuration section

        :param section: configuration section
        :param lst_config: key, value list of configurations
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.add_section_toFile(section)

        for option, value in lst_config:
            print(option, value)
            self.config_parser.set(section, option, value)


    def get_config_items_by_section(self, section):
        """
        Retrieves the configurations for a particular section

        :param section: INI file section
        :return: a list of name, value pairs for the options in the section
        """
        return self.config_parser.items(section)

    def remove_config_section(self, section):
        """
        Removes a configuration section from a file
        :param section: configuration section to remove
        :return: void
        """
        self.config_parser.remove_section(section)

    def remove_options_from_section(self, section, lst_options):
        """
        Removes a list of options from configuration section
        :param section: configuration section in file
        :param lst_options: list of options to remove
        :return: void
        """
        for option, value in lst_options:
            self.config_parser.remove_option(section, option)

    def write_file(self, file, delimiter=True):
        with open(file, 'w') as f:
            self.config_parser.write(f, delimiter)


Я добавил функции, которые обертывают функции из API configParser, которые помогут выполнить то, что вы пытаетесь найти в этих разделах API add_section & set вместе с remove_section & remove_option

Чтобы использовать его, вы можете создать свой экземпляр и вызвать его с чем-то вроде:

from config_parser import MyConfigParser


def main():
    lst_section = []

    fileIn = './test1.conf'
    fileOut = './test2.conf'

    parser1 = MyConfigParser()
    parser2 = MyConfigParser()

    parser1.read_ini_file(fileIn)
    parser2.read_ini_file(fileOut)

    lst_section = parser1.get_config_items_by_section('1414')

    parser2.add_section_toFile('1414')
    parser2.add_configurations_to_section('1414', lst_section)

    parser1.remove_config_section('1414')

    parser1.write_file(fileIn)
    parser2.write_file(fileOut)


if __name__ == "__main__":
    main()

Класс MyConfigParser был быстрой сборкой, поэтому, если вы собираетесь использовать его в среде производственного типа, вы захотите добавить более надежную обработку ошибок, чтобы отслеживать такие вещи, как, если опция section уже существует. API-интерфейс configParser обычно показывает, какая ошибка возникнет, но вы можете попытаться / исключить обработку этого типа исключения. Если я не допустил ошибку в копировальной пасте, я закончил тем, что собрал что-то, что смог протестировать, чтобы оно работало для вас. Надеюсь, это поможет.

...