2012-09-06 95 views
4

我想用python解析erlang配置文件。有沒有一個模塊?這個配置文件包含;用Python解析Erlang配置文件

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

爲什麼不火了一個Erlang SH讓它爲你做格式化?我知道,不是在python中,但它會捕獲角落案例,並使python方面的解析變得非常簡單。 – selle

+0

我沒有建議python,但這是一個通過erl控制檯和unix腳本進行驗證的帖子http://stackoverflow.com/questions/13423387/how-do-i-validate-an-erlang-config-file -from-A-Linux的命令 – Eric

回答

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