python - 无法使用 ConfigParser 定位配置

标签 python linux

我试图打开一个配置文件,读取一个值,然后使用该值打开另一个配置文件。具体来说,我的配置文件位于 $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/

相关文章:

python - 删除 Pandas 中重复 NaN 值超过阈值的行

python - 如何从有序字典中选择最佳对?

python - 安装python3-dev时出现的问题

linux - Laravel 权限被拒绝 Centos 7

c# - .Net 核心互操作性 Linux

linux - 管道运算符是否修改其输入/输出?还是 ls 知道管道?

python - 如何解析xsd :dateTime format?

Python ctypes.WinDLL 错误,找不到 _dlopen(self._name, mode)

python - R_ext/事件循环.h : No such file error while installing rpy2 using pip

linux - 通过以太网电缆从笔记本电脑访问 couchdb 时访问被拒绝