我试图打开一个配置文件,读取一个值,然后使用该值打开另一个配置文件。具体来说,我的配置文件位于 $HOME/bin/config 下名为 Profile.ini 的文件中。然后,这会告诉我是否应该打开另一个名为 Configuration.ini 的配置,该配置位于 $HOME/bin/config/config1、$HOME/bin/config/config2 中。 python 代码本身是从 $HOME/TestSystems 运行的。但是,当我尝试运行这段代码时,它最终找不到配置文件并且无法打开它。下面是我的代码:
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)
当我运行这段代码时,我得到以下输出:
$HOME/bin/config/Profile.ini
Traceback (most recent call last):
activeProfile = path.get('Profiles', 'ActiveProfile')
ConfigParser.NoSectionError: No section: 'Profiles'
这意味着此代码未找到配置并正确打开它。我试图弄清楚这段代码有什么问题,以及我需要做什么才能使其正常工作
最佳答案
那是因为你试图在 python 中使用 shell 变量。
我冒昧地根据 PEP8 的标准稍微调整了你的代码(包括错误修复):
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)
关于python - 无法使用 ConfigParser 定位配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46331079/