В pyhocon есть возможность включить файл во время выполнения - PullRequest
0 голосов
/ 11 февраля 2019

Можно ли в pyhocon включить файл во время выполнения?

Я знаю, как объединить деревья во время выполнения, например,

conf = ConfigFactory.parse_file(conf_file)
conf1 = ConfigFactory.parse_file(include_conf)
conf = ConfigTree.merge_configs(conf, conf1)

Я хотел бы эмулировать оператор включения так, чтобыПеременные hocon вычисляются во время выполнения, как показано в приведенном ниже коде:

conf = ConfigFactory.parse_files([conf_file, include_conf])

1 Ответ

0 голосов
/ 11 февраля 2019

Можно использовать строки:

from pyhocon import ConfigFactory

# readingconf entrypoint
file = open('application.conf', mode='r')
conf_string = file.read()
file.close()

conf_string_ready = conf_string.replace("PATH_TO_CONFIG","spec.conf")
conf = ConfigFactory.parse_string(conf_string_ready)

print(conf)

application.conf имеет

include "file://INCLUDE_FILE"

или во время выполнения без подготовки я написал это сам, используя python 3.65:

#!/usr/bin/env python

import os
from pyhocon import ConfigFactory as Cf


def is_line_in_file(full_path, line):

    with open(full_path) as f:
        content = f.readlines()

        for l in content:
            if line in l:
               f.close()
               return True

        return False


 def line_prepender(filename, line, once=True):

    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)

        if is_line_in_file(filename, line) and once:
             return

        f.write(line.rstrip('\r\n') + '\n' + content)


 def include_configs(base_path, included_paths):

     for included_path in included_paths:

         line_prepender(filename=base_path, line=f'include file("{included_path}")')

     return Cf.parse_file(base_path)


if __name__ == "__main__":

    dir_path = os.path.dirname(os.path.realpath(__file__))
    print(f"current working dir: {dir_path}")

    dir_path = ''

    _base_path = f'{dir_path}example.conf'
    _included_files = [f'{dir_path}example1.conf', f'{dir_path}example2.conf']

    _conf = include_configs(base_path=_base_path, included_paths=_included_files)

    print('break point')
...