How to use the configparser.SafeConfigParser function in configparser

To help you get started, we’ve selected a few configparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chaoss / grimoirelab-sortinghat / sortinghat / cmd / config.py View on Github external
Writes 'value' on 'key' to the configuration file given in
        'filepath'. Configuration parameter in 'key' must follow the schema
        <section>.<option> .

        :param key: key to set
        :param value: value to set
        :param filepath: configuration file
        """
        if not filepath:
            raise RuntimeError("Configuration file not given")

        if not self.__check_config_key(key):
            raise RuntimeError("%s parameter does not exists or cannot be set" % key)

        config = configparser.SafeConfigParser()

        if os.path.isfile(filepath):
            config.read(filepath)

        section, option = key.split('.')

        if section not in config.sections():
            config.add_section(section)

        try:
            config.set(section, option, value)
        except TypeError as e:
            raise RuntimeError(str(e))

        try:
            with open(filepath, 'w') as f:</option></section>
github pcubillos / mc3 / MCcubed / rednoise / prayer.py View on Github external
of data points.
  savefile: String
    Name of file where to store the prayer-bead results.

  Notes
  -----
  Believing in a prayer bead is a mere act of faith, we are scientists
  for god's sake!
  """

  print("Believing in prayer beads is a mere act of faith, "
        "please don't use it\nfor published articles (Cubillos et al. 2017).")
  return None

  # Here's the code.
  config = configparser.SafeConfigParser()
  config.read([configfile])
  cfgsec = "MCMC"

  data = mu.parray(config.get(cfgsec, 'data'))
  if isinstance(data[0], str):
    array = mu.loadbin(data[0])
    data = array[0]
    if len(array) == 2:
      uncert = array[1]
    else:
      uncert = mu.parray(config.get(cfgsec, 'uncert'))

  params    = mu.parray(config.get(cfgsec, 'params'))
  if isinstance(params[0], str):
    array = mu.loadascii(params[0])
    ninfo, nparams = np.shape(array)
github wwyaiykycnf / e621dl / lib / config.py View on Github external
def __ini_to_dict__(self, fp):
        config = {}
        parser = configparser.SafeConfigParser()
        
        parser.read_file(fp)

        config['lastrun']     = parser.get(GEN,'lastrun')
        config['format']      = parser.get(GEN,'format')
        config['duplicates']  = parser.getboolean(GEN,'duplicates')

        config[ENG] = {}

        for engine_name in ENGINES.keys():
            engine_section = {}
            error = None
            try:
                engine_section['state']       = parser.getboolean(engine_name, 'state')
                engine_section['tags']        = parser.get(engine_name,'tags')
                engine_section['blacklist']   = parser.get(engine_name,'blacklist')
github olcf / pcircle / legacy / versioneer.py View on Github external
def get_config_from_root(root):
    """Read the project setup.cfg file to determine Versioneer config."""
    # This might raise EnvironmentError (if setup.cfg is missing), or
    # configparser.NoSectionError (if it lacks a [versioneer] section), or
    # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
    # the top of versioneer.py for instructions on writing your setup.cfg .
    setup_cfg = os.path.join(root, "setup.cfg")
    parser = configparser.SafeConfigParser()
    with open(setup_cfg, "r") as f:
        parser.readfp(f)
    VCS = parser.get("versioneer", "VCS")  # mandatory

    def get(parser, name):
        if parser.has_option("versioneer", name):
            return parser.get("versioneer", name)
        return None
    cfg = VersioneerConfig()
    cfg.VCS = VCS
    cfg.style = get(parser, "style") or ""
    cfg.versionfile_source = get(parser, "versionfile_source")
    cfg.versionfile_build = get(parser, "versionfile_build")
    cfg.tag_prefix = get(parser, "tag_prefix")
    if cfg.tag_prefix in ("''", '""'):
        cfg.tag_prefix = ""
github MozillaSecurity / funfuzz / src / funfuzz / util / download_build.py View on Github external
downloadedShellCfg.set('Main', 'product', 'mozilla-aurora')
    elif 'mozilla-beta-' in urlLink:
        downloadedShellCfg.set('Main', 'product', 'mozilla-beta')
    elif 'mozilla-release-' in urlLink:
        downloadedShellCfg.set('Main', 'product', 'mozilla-release')
    elif 'mozilla-esr52-' in urlLink:
        downloadedShellCfg.set('Main', 'product', 'mozilla-esr52')
    downloadedShellCfg.set('Main', 'os', osname)

    downloadedShellFMConfPath = os.path.join(bDir, 'dist', 'js.fuzzmanagerconf')  # pylint: disable=invalid-name
    if not os.path.isfile(downloadedShellFMConfPath):
        with open(downloadedShellFMConfPath, 'w') as cfgfile:
            downloadedShellCfg.write(cfgfile)

    # Required pieces of the .fuzzmanagerconf file are platform, product and os
    cfg = configparser.SafeConfigParser()
    cfg.read(downloadedShellFMConfPath)
    assert cfg.get('Main', 'platform')
    assert cfg.get('Main', 'product')
    assert cfg.get('Main', 'os')
github nict-csl / exist / scripts / insert2db / reputation / plugins / bambenek_ip.py View on Github external
import sys
import os
import configparser
import requests
import pandas as pd
import hashlib
from io import StringIO
from datetime import datetime, timezone

## Django Setup
import django
import pymysql
pymysql.install_as_MySQLdb()
conffile = os.path.join(os.path.dirname(__file__), "../../conf/insert2db.conf")
conf = configparser.SafeConfigParser()
conf.read(conffile)
sys.path.append(conf.get('exist', 'syspath'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intelligence.settings')
django.setup()
from apps.reputation.models import blacklist
import django.utils.timezone as tzone
from django.db import IntegrityError

## Logger Setup
from logging import getLogger, DEBUG, NullHandler
logger = getLogger(__name__)
logger.addHandler(NullHandler())
logger.setLevel(DEBUG)
logger.propagate = True

DataDir = os.path.join(os.path.dirname(__file__), '../data/')
github NeCTAR-RC / nectar-tools / nectar_tools / config.py View on Github external
def read(self, filename):
        if not os.path.isfile(filename):
            print("Config file %s not found." % filename, file=sys.stderr)
            return
        conf = configparser.SafeConfigParser()
        conf.read(filename)
        self['DEFAULT'] = AttrDict(conf.defaults())
        for section in conf.sections():
            self[section] = AttrDict(conf.items(section))
github dpoulson / r2_control / Hardware / Lights / FlthyHPControl.py View on Github external
from future import standard_library
import smbus
import os
import datetime
import time
from r2utils import mainconfig
from flask import Blueprint, request
import configparser
standard_library.install_aliases()
from builtins import hex
from builtins import object


_configfile = mainconfig.mainconfig['config_dir'] + 'flthy.cfg'

_config = configparser.SafeConfigParser({'address': '0x19',
                                         'logfile': 'flthy.log',
                                         'reeltwo': 'false'})
if not os.path.isfile(_configfile):
    print("Config file does not exist")
    with open(_configfile, 'wt') as configfile:
        _config.write(configfile)

_config.read(_configfile)

_defaults = _config.defaults()

_hp_list = ['top', 'front', 'rear', 'back', 'all']
_type_list = ['light', 'servo']
_sequence_list = ['leia', 'projector', 'dimpulse', 'cycle', 'shortcircuit', 'colour', 'rainbow', 'disable', 'enable']
_colour_list = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta', 'orange', 'purple', 'white', 'random']
_position_list = ['top', 'bottom', 'center', 'left', 'right']
github nict-csl / exist / lib / abuse.py View on Github external
def __init__(self):
        conffile = 'conf/exist.conf'
        conf = configparser.SafeConfigParser()
        conf.read(conffile)
        self.__baseURL = conf.get('abuse', 'baseURL')
        self.__key = conf.get('abuse', 'apikey')
github cjaymes / pyscap / scap / CredentialStore.py View on Github external
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PySCAP.  If not, see .

import logging, configparser, sys

logger = logging.getLogger(__name__)
class CredentialStore(object):
    class __OnlyOne(configparser.SafeConfigParser):
        pass

    instance = None
    def __init__(self):
        if not CredentialStore.instance:
            CredentialStore.instance = CredentialStore.__OnlyOne()

    def __getattr__(self, name):
        if not CredentialStore.instance:
            CredentialStore.instance = CredentialStore.__OnlyOne()
        return getattr(self.instance, name)