【问题标题】:Parsing Erlang Config file with Python用 Python 解析 Erlang 配置文件
【发布时间】:2012-08-31 01:47:19
【问题描述】:

我想在 python 中解析一个 erlang 配置文件。有它的模块吗?该配置文件包含;

[{webmachine, [
 {bind_address, "12.34.56.78"},
 {port, 12345},
 {document_root, "foo/bar"}
]}].

【问题讨论】:

  • 为什么不启动一个 erlang shell 并让它为你进行格式化呢?我知道,不是在 python 中,但它会捕捉到极端情况并使 python 端的解析变得超级简单。
  • 我对 python 没有建议,但这里有一篇关于通过 erl 控制台和 unix 脚本进行验证的帖子stackoverflow.com/questions/13423387/…

标签: python parsing erlang


【解决方案1】:

您可以使用 etf 库在 python https://github.com/machinezone/python_etf 中解析 erlang 术语

【讨论】:

    【解决方案2】:

    未经测试且有点粗糙,但对您的示例“有效”

    import re
    from ast import literal_eval
    
    input_string = """
    [{webmachine, [ 
     {bind_address, "12.34.56.78"}, 
     {port, 12345}, 
     {document_root, "foo/bar"} 
    ]}]
    """
    
    # make string somewhat more compatible with Python syntax:
    compat = re.sub('([a-zA-Z].*?),', r'"\1":', input_string)
    
    # evaluate as literal, see what we get
    res = literal_eval(compat)
    
    [{'webmachine': [{'bind_address': '12.34.56.78'}, {'port': 12345},
    {'document_root': 'foo/bar'}]}]
    

    然后您可以将字典列表“汇总”成一个简单的dict,例如:

    dict(d.items()[0] for d in res[0]['webmachine'])
    
    {'bind_address': '12.34.56.78', 'port': 12345, 'document_root':
    'foo/bar'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2021-06-16
      • 2021-08-14
      相关资源
      最近更新 更多