使用Python解析Erlang配置文件

时间:2012-09-06 09:12:29

标签: python parsing erlang

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

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

2 个答案:

答案 0 :(得分:4)

未经测试且有点粗糙,但“适用于您的示例”

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'}

答案 1 :(得分:4)

您可以使用etf库来解析python https://github.com/machinezone/python_etf

中的erlang术语