Alperen Elhan
Alperen Elhan

Reputation: 410

Parsing Erlang Config file with Python

I want to parse an erlang config file in python. Is there a module for it? This config file contains;

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

Upvotes: 4

Views: 1687

Answers (2)

Jon Clements
Jon Clements

Reputation: 142116

Untested and a little rough, but 'works' on your example

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

You could then "roll-up" the list of dictionary into a simple dict, eg:

dict(d.items()[0] for d in res[0]['webmachine'])

{'bind_address': '12.34.56.78', 'port': 12345, 'document_root':
'foo/bar'}

Upvotes: 4

Andrey Vasenin
Andrey Vasenin

Reputation: 131

You could use etf library to parse erlang terms in python https://github.com/machinezone/python_etf

Upvotes: 4

Related Questions