【问题标题】:PyYaml parsing of the Environment variable in the Yaml configuration fileYaml配置文件中环境变量的PyYaml解析
【发布时间】:2014-11-03 10:14:24
【问题描述】:

我需要阅读以下 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

但是,例如,在结果字符串中关闭 我需要获取相关路径。 对于加载此文件,我使用以下代码:

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

我怎样才能得到所需的结果? Tnx。

【问题讨论】:

    标签: python env pyyaml


    【解决方案1】:

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

    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'] )
    

    【讨论】:

    • 感谢您的回答,尽管我遇到了 int 的问题,在上面的示例中,对于 backupCount,它会出现 '7' 而不是 7。你是如何解决的? @ganeshsamant
    猜你喜欢
    • 2021-04-01
    • 2021-05-17
    • 2021-07-14
    • 2022-11-28
    • 2017-06-12
    • 2018-04-28
    • 1970-01-01
    • 2012-02-16
    • 2020-12-04
    相关资源
    最近更新 更多