dgBP
dgBP

Reputation: 1691

How to open an ini config file from filename stored in another ini config file?

I seem to be having a problem that doesn't feel like it is a problem, but I can't see the solution so maybe someone else can.

I'm using an ini file to store config details for a package I'm writing. This ini file comprises of sections relating to other ini files.

There are plenty of other ways for doing this I know, but I have chosen this method because I like how clear the config setup is. And in theory it should be simple.

So in my main.ini file I have something like:

[topic_name1]
file_name = 'configSetupFiles/topic_name1.ini'
[topic_name2]
file_name = 'configSetupFiles/topic_name2.ini'

Then in topic_name1.ini I have a setup in a basic form like:

[topic]
url = 'http://blah.com'
param1 = 10

[another_section]
href = 'x/y?z=yes'

topic_name2.ini follows the same format.

So what I'm trying to do is this:

#!/usr/bin/env python3
fromgent_epid configparser import SafeConfigParser
import os

iniparser = SafeConfigParser(os.environ)
config = {}
iniparser.read('main.ini')
for c in iniparser.sections():
    config[c] = iniparser.get(c, 'file_name')

for val in config.values():
    print(val) # prints file names without a problem
    inip = SafeConfigParser(os.environ)
    inip.read(val)
    for s in inip.sections():
        print("Section:", s)

I don't get an error running this; it prints val but then no sign of anything else.When I go to hardcode in the file name it prints without a problem. But then when I print out the keys of the sections of topic_name ini files, I get a stream of keys like so:

url
param1
gdmsession
gpg_agent
xmodifiers
java_bindir
gtk_modules
ostype
xsession_is_up
cshedit
user
...

code:

inip = SafeConfigParser(os.environ)
inip.read('configSetupFiles/topic_name1.ini')
for field in inip.sections():
    print(field)
    for k in inip[field]:
        print(k)

I want to print out the keys because there might be different field names in each file & section so I cannot reference them directly and use .get.

Is there a conflict when creating a second ConfigParser instance this way? I really don't understand why it isn't just working. Apologies if I've missed some info, been staring at this too long. Any help appreciated.

Upvotes: 1

Views: 413

Answers (1)

Mark Ignacio
Mark Ignacio

Reputation: 431

No problem with the code! Just a problem with your .ini file.

Remove the quotes inside of main.ini.

[topic_name1]
file_name = configSetupFiles/topic_name1.ini
[topic_name2]
file_name = configSetupFiles/topic_name2.ini

Upvotes: 1

Related Questions