简体   繁体   English

如何使用configparser对象获取配置文件路径

[英]How to get configuration file path with configparser object

The code below initiates the conf variable which is an instance of the Configuration class which inherits from ConfigParser . 下面的代码启动conf变量,该变量是Configuration类的实例,该类继承自ConfigParser In its __init__ method it reads the config_file and stores its configuration context in a memory. 它使用__init__方法读取config_file并将其配置上下文存储在内存中。 How can I get a file path to this config_file having conf object? 如何获取具有conf对象的config_file的文件路径?

import ConfigParser
import os 


class Configuration(ConfigParser.ConfigParser):
    def __init__(self, config_file):
        ConfigParser.ConfigParser.__init__(self) 
        self.read(config_file)

    def saveSettings(self):
        if not self.has_section('Section A'):
            self.add_section('Section A')
        self.set('Section A', 'Option 1', 'Value 1')

config_file = os.path.join(os.path.expanduser('~'),'config.ini' )
conf = Configuration(config_file)
conf.saveSettings()

Simply assign the information to the instance ( self ): 只需将信息分配给实例( self ):

def __init__(self, config_path):
    ConfigParser.ConfigParser.__init__(self) 
    self.read(config_path)
    self.config_path = config_path # this is now an instance attribute

then you can access it with the object: 那么您可以使用对象访问它:

conf_path = os.path.join(os.path.expanduser('~'),'config.ini' )
conf = Configuration(conf_path)

print( conf.conf_path ) # access via object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM