python - PyYaml解析Yaml配置文件中的Environment变量

标签 python env pyyaml

我需要阅读以下 yaml 格式的配置文件:

version: 1
disable_existing_loggers: False
formatters:
  precise:
    format: "%(name)-15s # %(levelname)-8s # %(asctime)s # [Line: %(lineno)-3d]: %(message)s"
    datefmt: "%Y-%m-%d %H:%M:%S"
handlers:
  file:
    class:        logging.handlers.RotatingFileHandler
    filename:     <%= ENV['ENV_PROJECT'] %>/target/tracing.log
    encoding:     utf-8
    maxBytes :    10737418244
    backupCount:  7
    formatter:    precise
loggers:
  utility:
    handlers:     [file]
    level:        INFO
    propagate:    True
root:
  handlers:       [file]
  level:          INFO

但是,例如,我需要在结果字符串中关闭 <%= ENV['ENV_PROJECT'] %> 以获得相关路径。 为了加载此文件,我使用以下代码:

from yaml import load
with open('test.yml', 'rt') as stream:
    configuration = load(stream)

如何获得所需的结果? 谢谢。

最佳答案

您需要使用“解析器”和“构造器”来实现这一点。这是实现此目的的一种方法。

import yaml, os, re

#define the regex pattern that the parser will use to 'implicitely' tag your node
pattern = re.compile( r'^\<%= ENV\[\'(.*)\'\] %\>(.*)$' )

#now define a custom tag ( say pathex ) and associate the regex pattern we defined
yaml.add_implicit_resolver ( "!pathex", pattern )

#at this point the parser will associate '!pathex' tag whenever the node matches the pattern

#you need to now define a constructor that the parser will invoke
#you can do whatever you want with the node value
def pathex_constructor(loader,node):
  value = loader.construct_scalar(node)
  envVar, remainingPath = pattern.match(value).groups()
  return os.environ[envVar] + remainingPath

#'register' the constructor so that the parser will invoke 'pathex_constructor' for each node '!pathex'
yaml.add_constructor('!pathex', pathex_constructor)

#that is it

data = """
version: 1
disable_existing_loggers: False
formatters:
  precise:
    format: "%(name)-15s # %(levelname)-8s # %(asctime)s # [Line: %(lineno)-3d]: %(message)s"
    datefmt: "%Y-%m-%d %H:%M:%S"
handlers:
  file:
    class:        logging.handlers.RotatingFileHandler
    filename:     <%= ENV['ENV_PROJECT'] %>/target/tracing.log 
    encoding:     utf-8
    maxBytes :    10737418244
    backupCount:  7
    formatter:    precise
loggers:
  utility:
    handlers:     [file]
    level:        INFO
    propagate:    True
root:
  handlers:       [file]
  level:          INFO
"""

deSerializedData = yaml.load(data)

print(deSerializedData [ 'handlers'] [ 'file' ] ['filename'] )

关于python - PyYaml解析Yaml配置文件中的Environment变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26712003/

相关文章:

Python (django) 环境变量

python - Pyyaml 转储不会为相同对象生成 anchor

python - 如何使用来自另一个字典中匹配键的值更新 YAML 文件?

python - 为包含 : join table on itself with selecting all column of 1st table and some column of right table 的 sql 查询制作等效的 pandas 数据框

python - PyCharm 5 导入错误

python - 如何从子窗口小部件类中打印父窗口小部件的名称?

flash - 在 AS3 中确定 Flash 上下文的最佳方法?

python - 将格式化字符串转换为日期时间

javascript - 如何将环境变量转换为 JS 中的对象?

python - 为什么在导入 yaml 文件时遍历生成器对象后内容被删除