Reputation: 355
I am attempting to open a configuration file, read a value, and then use that value to open another configuration file. Specifically, my config files are located under $HOME/bin/config, in a file named Profile.ini. Then, this gives me the info of whether I should be opening another config named Configuration.ini that is located in either $HOME/bin/config/config1, $HOME/bin/config/config2. The python code itself is being run from $HOME/TestSystems. However, when I attempt to run this code, it ends up not finding the configuration file and being unable to open it. Below is my code:
import ConfigParser
class ConfigManager(object):
"""docstring for ConfigManager."""
def __init__(self):
super(ConfigManager, self).__init__()
self.path = '$HOME/bin/config/'
def getConfig(self):
path = ConfigParser.ConfigParser()
print self.path+'Profile.ini'
path.read(self.path+'Profile.ini')
for sectionName in path.sections():
print 'Section:', sectionName
print ' Options:', path.options(sectionName)
for name, value in path.items(sectionName):
print ' %s = %s' % (name, value)
print
activeProfile = path.get('Profiles', 'ActiveProfile')
configPath = self.path + activeProfile + '/Configuration.ini'
config = ConfigParser.ConfigParser()
configProfile = config.read(configPath)
When I run this code, I get the following output:
$HOME/bin/config/Profile.ini
Traceback (most recent call last):
activeProfile = path.get('Profiles', 'ActiveProfile')
ConfigParser.NoSectionError: No section: 'Profiles'
Which means that this code isn't finding the configuration and opening it properly. I'm trying to figure out what is wrong with this code and what I need to do to make it work properly
Upvotes: 0
Views: 1333
Reputation: 1608
That's because you are trying to use the shell variables in the python.
I took the liberty of slightly adjusting your code according to the standard of PEP8 ( including bug fix ):
import ConfigParser
import os
class ConfigManager(object):
"""docstring for ConfigManager."""
def __init__(self):
super(ConfigManager, self).__init__()
self.path = os.path.join(
os.environ['HOME'],
'bin/config'
)
def get_config(self):
parser = ConfigParser.ConfigParser()
print(os.path.join(self.path, 'Profile.ini'))
parser.read(
os.path.join(self.path, 'Profile.ini')
)
for section_name in parser.sections():
print('Section:', section_name)
print(' Options:', parser.options(section_name))
for name, value in parser.items(section_name):
print(' %s = %s' % (name, value))
print()
config_path = os.path.join(
self.path,
parser.get('Profiles', 'ActiveProfile'),
'Configuration.ini'
)
config_profile = parser.read(config_path)
print(config_profile)
Upvotes: 2