[英]Unable to locate a config with ConfigParser
我試圖打開配置文件,讀取一個值,然后使用該值打開另一個配置文件。 具體來說,我的配置文件位於$ HOME / bin / config下的Profile.ini文件中。 然后,這為我提供了是否應該打開位於$ HOME / bin / config / config1,$ HOME / bin / config / config2中的另一個名為Configuration.ini的配置的信息。 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的標准(包括bug修復)對您的代碼進行一些調整:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.