0

php Yaconf can read .ini file

a=123
b=45
c.e.f=987

output like

['a' => 123]
['b' => 45]
['c' =>['e'=>['f'=>987]]]

can python read like this?

thx


Hi, All, May be I did not describe the question well, Sorry for that

Firstly, I did tried configparser, which just parse config key=value. But I would have config like a.b.c=value, e.g:

[cache]
redis.master.host='10.10.10.10'
redis.master.port='6379'
redis.master.auth='xxxx'
redis.slave_1.host='10.10.10.12'
redis.slave_1.port='6389'
redis.slave_1.auth='xxxx'

So, I would read config like

cfger.get('cache', 'redis')

and hope get result like

{'redis': {
    'master': {
           'host': '10.10.10.10',
           'port': '6379',
           'auth': 'xxxx',
        },
     'slave_1': {
           'host': '10.10.10.12',
           'port': '6389',
           'auth': 'xxxx',
        },
     }
}

Hope you can know what I said

Tony_Wang
  • 133
  • 1
  • 1
  • 9
  • It certainly could, if you programmed it to do so. Have you tried something you could show us? – Lysandros Nikolaou Apr 14 '17 at 14:23
  • @LysandrosNikolaou thx for your reply! I have tried configparser. however, it just parse key=value, not key1.key2.key3=value – Tony_Wang Apr 14 '17 at 14:26
  • 1
    maybe this could be helpful (4th answer) http://stackoverflow.com/questions/8884188/how-to-read-and-write-ini-file-with-python3 – Astrom Apr 14 '17 at 14:31
  • I think what you are looking for is sections in .ini files. You should take a look at [configObj](http://configobj.readthedocs.io/en/latest/configobj.html#the-config-file-format). – Lysandros Nikolaou Apr 14 '17 at 14:36
  • @Tony_Wang, Lysandros is right: The answer to the **question you asked** is "configparser". If it doesn't solve the problem you have, **edit your question** to ask more clearly, and be sure to demonstrate why `configparser` fails. (Did you try `configparser`? What happened? Answer both questions if you edit your question.) – alexis Apr 14 '17 at 14:45

1 Answers1

0

Yes it is possible. I will not go so deep. Use belove snippet as boilerplate.

$ cat some.ini 
a=123
b=45
c.e.f=987

...
>>>h = {}
>>>l = []
>>> with open('some.ini') as inifile:
...     for lines in inifile.readlines():
...         k,v = lines.split('=')
...         h[k] = int(v)
...         # or l.append([lines.strip()])  
>>> h
{'a': 123, 'c.e.f': 987, 'b': 45}

the only thing you have to do is, parse 'c.e.f' to a nested dict.

marmeladze
  • 6,468
  • 3
  • 24
  • 45