Pretty late, but maybe it can help someone else look for the same answers that I recently received. In addition, one of the comments was on how to get environment variables and values ββfrom other sections. This is how I deal with the conversion of environment variables and multi-section tags when reading from an INI file.
INI FILE:
[PKG] # <VARIABLE_NAME>=<VAR/PATH> PKG_TAG = Q1_RC1 [DELIVERY_DIRS] # <DIR_VARIABLE>=<PATH> NEW_DELIVERY_DIR=${DEL_PATH}\ProjectName_${PKG:PKG_TAG}_DELIVERY
A Python class that uses ExtendedInterpolation so you can use formatting like ${PKG:PKG_TAG} . I am adding the ability to convert Windows environment variables when I read in INI into a string using the built-in os.path.expandvars() such as ${DEL_PATH} above.
import os from configparser import ConfigParser, ExtendedInterpolation class ConfigParser(object): def __init__(self): """ initialize the file parser with ExtendedInterpolation to use ${Section:option} format [Section] option=variable """ self.config_parser = ConfigParser(interpolation=ExtendedInterpolation()) def read_ini_file(self, file='./config.ini'): """ Parses in the passed in INI file and converts any Windows environ vars. :param file: INI file to parse :return: void """ # Expands Windows environment variable paths with open(file, 'r') as cfg_file: cfg_txt = os.path.expandvars(cfg_file.read()) # Parses the expanded config string self.config_parser.read_string(cfg_txt) def get_config_items_by_section(self, section): """ Retrieves the configurations for a particular section :param section: INI file section :return: a list of name, value pairs for the options in the section """ return self.config_parser.items(section) def get_config_val(self, section, option): """ Get an option value for the named section. :param section: INI section :param option: option tag for desired value :return: Value of option tag """ return self.config_parser.get(section, option) @staticmethod def get_date(): """ Sets up a date formatted string. :return: Date string """ return datetime.now().strftime("%Y%b%d") def prepend_date_to_var(self, sect, option): """ Function that allows the ability to prepend a date to a section variable. :param sect: INI section to look for variable :param option: INI search variable under INI section :return: Void - Date is prepended to variable string in INI """ if self.config_parser.get(sect, option): var = self.config_parser.get(sect, option) var_with_date = var + '_' + self.get_date() self.config_parser.set(sect, option, var_with_date)
L0ngSh0t
source share