Python ConfigParser.ConfigParser.get() Examples

The following are 23 code examples of ConfigParser.ConfigParser.get(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ConfigParser.ConfigParser , or try the search function .
Example #1
Source File: parser.py    From pibooth with MIT License 6 votes vote down vote up
def save(self, default=False):
        """Save the current or default values into the configuration file.
        """
        LOGGER.info("Generate the configuration file in '%s'", self.filename)

        dirname = osp.dirname(self.filename)
        if not osp.isdir(dirname):
            os.makedirs(dirname)

        with io.open(self.filename, 'w', encoding="utf-8") as fp:
            for section, options in DEFAULT.items():
                fp.write("[{}]\n".format(section))
                for name, value in options.items():
                    if default:
                        val = value[0]
                    else:
                        val = self.get(section, name)
                    fp.write("# {}\n{} = {}\n\n".format(value[1], name, val))

        self.handle_autostart() 
Example #2
Source File: testutils.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def getstringlist(self, section, option):
        "Coerce option to a list of strings or return unchanged if that fails."

        value = ConfigParser.get(self, section, option)

        # This seems to allow for newlines inside values
        # of the config file, but be careful!!
        val = string.replace(value, '\n', '')

        if self.pat.match(val):
            return eval(val)
        else:
            return value


# This class as suggested by /F with an additional hook
# to be able to filter filenames. 
Example #3
Source File: testutils.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def getstringlist(self, section, option):
        "Coerce option to a list of strings or return unchanged if that fails."

        value = ConfigParser.get(self, section, option)

        # This seems to allow for newlines inside values
        # of the config file, but be careful!!
        val = value.replace('\n', '')

        if self.pat.match(val):
            return eval(val)
        else:
            return value


# This class as suggested by /F with an additional hook
# to be able to filter filenames. 
Example #4
Source File: config.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_secure_option(self, section, option):
        """Test an option to see if it is secured or not.

        :param section: section id
        :type section: string
        :param option: option name
        :type option: string
        :rtype: boolean
        otherwise.
        """
        if not self.has_section(section):
            return False
        if not self.has_option(section, option):
            return False
        if ConfigParser.get(self, section, option) == self._secure_placeholder:
            return True
        return False 
Example #5
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def name(self, value):
        old_name = self._name
        if value is old_name:
            return
        self._name = value
        configs = ConfigParser._named_configs

        if old_name:  # disconnect this parser from previously connected props
            _, props = configs.get(old_name, (None, []))
            for widget, prop in props:
                widget = widget()
                if widget:
                    widget.property(prop).set_config(None)
            configs[old_name] = (None, props)

        if not value:
            return

        # if given new name, connect it with property that used this name
        try:
            config, props = configs[value]
        except KeyError:
            configs[value] = (ref(self), [])
            return

        if config is not None:
            raise ValueError('A parser named {} already exists'.format(value))
        for widget, prop in props:
            widget = widget()
            if widget:
                widget.property(prop).set_config(self)
        configs[value] = (ref(self), props) 
Example #6
Source File: unicode_aware.py    From wot-teamspeak-mod with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get(self, section, option, *args, **kwargs):
		demand_unicode(section)
		demand_unicode(option)
		return to_unicode(ParentConfigParser.get(self, section, option, *args, **kwargs)) 
Example #7
Source File: parser.py    From pibooth with MIT License 5 votes vote down vote up
def getpath(self, section, option):
        """Get a path from config, evaluate the absolute path from configuration
        file path.

        :param section: config section name
        :type section: str
        :param option: option name
        :type option: str
        """
        return self._get_abs_path(self.get(section, option)) 
Example #8
Source File: parser.py    From pibooth with MIT License 5 votes vote down vote up
def gettyped(self, section, option):
        """Get a value from config and try to convert it in a native Python
        type (using the :py:mod:`ast` module).

        :param section: config section name
        :type section: str
        :param option: option name
        :type option: str
        """
        value = self.get(section, option)
        try:
            return ast.literal_eval(value)
        except (ValueError, SyntaxError):
            return value 
Example #9
Source File: parser.py    From pibooth with MIT License 5 votes vote down vote up
def get(self, section, option, **kwargs):
        """Override the default function of ConfigParser to add a
        default value if section or option is not found.

        :param section: config section name
        :type section: str
        :param option: option name
        :type option: str
        """
        if self.has_section(section) and self.has_option(section, option):
            return ConfigParser.get(self, section, option, **kwargs)
        return str(DEFAULT[section][option][0]) 
Example #10
Source File: testutils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def printLocation(depth=1):
    if sys._getframe(depth).f_locals.get('__name__')=='__main__':
        outDir = outputfile('')
        if outDir!=_OUTDIR:
            print 'Logs and output files written to folder "%s"' % outDir 
Example #11
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def name(self, value):
        old_name = self._name
        if value is old_name:
            return
        self._name = value
        configs = ConfigParser._named_configs

        if old_name:  # disconnect this parser from previously connected props
            _, props = configs.get(old_name, (None, []))
            for widget, prop in props:
                widget = widget()
                if widget:
                    widget.property(prop).set_config(None)
            configs[old_name] = (None, props)

        if not value:
            return

        # if given new name, connect it with property that used this name
        try:
            config, props = configs[value]
        except KeyError:
            configs[value] = (ref(self), [])
            return

        if config is not None:
            raise ValueError('A parser named {} already exists'.format(value))
        for widget, prop in props:
            widget = widget()
            if widget:
                widget.property(prop).set_config(self)
        configs[value] = (ref(self), props) 
Example #12
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def getdefault(self, section, option, defaultvalue):
        '''Get an option. If not found, it will return the default value.
        '''
        if not self.has_section(section):
            return defaultvalue
        if not self.has_option(section, option):
            return defaultvalue
        return self.get(section, option) 
Example #13
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def read(self, filename):
        '''Read only one filename. In contrast to the original ConfigParser of
        Python, this one is able to read only one file at a time. The last
        read file will be used for the :meth:`write` method.

        .. versionchanged:: 1.9.0
            :meth:`read` now calls the callbacks if read changed any values.

        '''
        if not isinstance(filename, string_types):
            raise Exception('Only one filename is accepted ({})'.format(
                string_types.__name__))
        self.filename = filename
        # If we try to open directly the configuration file in utf-8,
        # we correctly get the unicode value by default.
        # But, when we try to save it again, all the values we didn't changed
        # are still unicode, and then the PythonConfigParser internal do
        # a str() conversion -> fail.
        # Instead we currently to the conversion to utf-8 when value are
        # "get()", but we internally store them in ascii.
        #with codecs.open(filename, 'r', encoding='utf-8') as f:
        #    self.readfp(f)
        old_vals = {sect: {k: v for k, v in self.items(sect)} for sect in
                    self.sections()}
        PythonConfigParser.read(self, filename)

        # when reading new file, sections/keys are only increased, not removed
        f = self._do_callbacks
        for section in self.sections():
            if section not in old_vals:  # new section
                for k, v in self.items(section):
                    f(section, k, v)
                continue

            old_keys = old_vals[section]
            for k, v in self.items(section):  # just update new/changed keys
                if k not in old_keys or v != old_keys[k]:
                    f(section, k, v) 
Example #14
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def getdefault(self, section, option, defaultvalue):
        '''Get an option. If not found, it will return the default value.
        '''
        if not self.has_section(section):
            return defaultvalue
        if not self.has_option(section, option):
            return defaultvalue
        return self.get(section, option) 
Example #15
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def get(self, section, option, **kwargs):
        value = PythonConfigParser.get(self, section, option, **kwargs)
        if PY2:
            if type(value) is str:
                return value.decode('utf-8')
        return value 
Example #16
Source File: config.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def read(self, filename):
        '''Read only one filename. In contrast to the original ConfigParser of
        Python, this one is able to read only one file at a time. The last
        read file will be used for the :meth:`write` method.

        .. versionchanged:: 1.9.0
            :meth:`read` now calls the callbacks if read changed any values.

        '''
        if not isinstance(filename, string_types):
            raise Exception('Only one filename is accepted ({})'.format(
                string_types.__name__))
        self.filename = filename
        # If we try to open directly the configuration file in utf-8,
        # we correctly get the unicode value by default.
        # But, when we try to save it again, all the values we didn't changed
        # are still unicode, and then the PythonConfigParser internal do
        # a str() conversion -> fail.
        # Instead we currently to the conversion to utf-8 when value are
        # "get()", but we internally store them in ascii.
        #with codecs.open(filename, 'r', encoding='utf-8') as f:
        #    self.readfp(f)
        old_vals = {sect: {k: v for k, v in self.items(sect)} for sect in
                    self.sections()}
        PythonConfigParser.read(self, filename)

        # when reading new file, sections/keys are only increased, not removed
        f = self._do_callbacks
        for section in self.sections():
            if section not in old_vals:  # new section
                for k, v in self.items(section):
                    f(section, k, v)
                continue

            old_keys = old_vals[section]
            for k, v in self.items(section):  # just update new/changed keys
                if k not in old_keys or v != old_keys[k]:
                    f(section, k, v) 
Example #17
Source File: testutils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def printLocation(depth=1):
    if sys._getframe(depth).f_locals.get('__name__')=='__main__':
        outDir = outputfile('')
        if outDir!=_OUTDIR:
            print('Logs and output files written to folder "%s"' % outDir) 
Example #18
Source File: conf.py    From scapy-fakeap with GNU General Public License v2.0 5 votes vote down vote up
def get(self, key, default=None):
        value = None
        try:
            value = ConfigParser.get(self, 'fakeap', key)
        except NoOptionError as e:
            value = default
            printd("Option '%s' not specified in config file. Using default." % e.option, Level.WARNING)

        printd("%s -> %s" % (key, value), Level.INFO)

        return value 
Example #19
Source File: config.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def encrypt_account(self, id):
        """Make sure that certain fields are encrypted."""
        for key in self.secured_field_names:
            value = self.parser.get(id, key)
            self.parser.set_secure(id, key, value)
        return self 
Example #20
Source File: config.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, section, option, *args):
        """Get option value from section. If an option is secure,
        populates the plain text."""
        if self.is_secure_option(section, option) and self.keyring_available:
            s_option = "%s%s" % (section, option)
            if self._unsaved.get(s_option, [''])[0] == 'set':
                res = self._unsaved[s_option][1]
            else:
                res = keyring.get_password(self.keyring_name, s_option)
        else:
            res = ConfigParser.get(self, section, option, *args)
        if res == '!!False!!':
            return False
        return res 
Example #21
Source File: config.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_secure(self, section, option, value):
        """Set an option and mark it as secure.

        Any subsequent uses of 'set' or 'get' will also
        now know that this option is secure as well.
        """
        if self.keyring_available:
            s_option = "%s%s" % (section, option)
            self._unsaved[s_option] = ('set', value)
            value = self._secure_placeholder
        ConfigParser.set(self, section, option, value) 
Example #22
Source File: config.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def items(self, section):
        """Get all items for a section. Subclassed, to ensure secure
        items come back with the unencrypted data.

        :param section: section id
        :type section: string
        """
        items = []
        for k, v in ConfigParser.items(self, section):
            if self.is_secure_option(section, k):
                v = self.get(section, k)
            if v == '!!False!!':
                v = False
            items.append((k, v))
        return items 
Example #23
Source File: parser.py    From pibooth with MIT License 4 votes vote down vote up
def gettuple(self, section, option, types, extend=0):
        """Get a list of values from config. The values type shall be in the
        list of authorized types. This method permits to get severals values
        from the same configuration option.

        If the option contains one value (with acceptable type), a tuple
        with one element is created and returned.

        :param section: config section name
        :type section: str
        :param option: option name
        :type option: str
        :param types: list of authorized types
        :type types: list
        :param extend: extend the tuple with the last value until length is reached
        :type extend: int
        """
        values = self.gettyped(section, option)
        types, color, path = self._get_authorized_types(types)

        if not isinstance(values, (tuple, list)):
            if not isinstance(values, types):
                raise ValueError("Invalid config value [{}][{}]={}".format(section, option, values))
            values = (values,)
        else:
            # Check if one value is given or if it is a list of value
            if color and len(values) == 3 and all(isinstance(elem, int) for elem in values):
                values = (values,)
            elif not all(isinstance(elem, types) for elem in values):
                raise ValueError("Invalid config value [{}][{}]={}".format(section, option, values))

        if path:
            new_values = []
            for v in values:
                if isinstance(v, basestring):
                    new_values.append(self._get_abs_path(v))
                else:
                    new_values.append(v)
            values = tuple(new_values)

        while len(values) < extend:
            values += (values[-1],)
        return values