Python ConfigParser.RawConfigParser() Examples

The following are 30 code examples of ConfigParser.RawConfigParser(). 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 , or try the search function .
Example #1
Source File: system_info.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #2
Source File: system_info.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #3
Source File: system_info.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #4
Source File: system_info.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #5
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #6
Source File: mysql_cnf_builder.py    From mysql_utils with GNU General Public License v2.0 6 votes vote down vote up
def create_skip_replication_cnf(override_dir=None):
    """ Create a secondary cnf file that will allow for mysql to skip
        replication start. Useful for running mysql upgrade, etc...

    Args:
    override_dir - Write to this directory rather than CNF_DIR
    """
    skip_replication_parser = ConfigParser.RawConfigParser(allow_no_value=True)
    skip_replication_parser.add_section(MYSQLD_SECTION)
    skip_replication_parser.set(MYSQLD_SECTION, 'skip_slave_start', None)
    if override_dir:
        skip_slave_path = os.path.join(override_dir,
                                       os.path.basename(host_utils.MYSQL_NOREPL_CNF_FILE))
    else:
        skip_slave_path = host_utils.MYSQL_NOREPL_CNF_FILE
    log.info('Writing file {skip_slave_path}'
             ''.format(skip_slave_path=skip_slave_path))
    with open(skip_slave_path, "w") as skip_slave_handle:
            skip_replication_parser.write(skip_slave_handle) 
Example #7
Source File: srmdumps.py    From rucio with Apache License 2.0 6 votes vote down vote up
def generate_url(rse, config):
    '''
    :param rse: Name of the endpoint.
    :param config: RawConfigParser instance which may have configuration
    related to the endpoint.
    :returns: Tuple with the URL where the links can be queried to find new
    dumps and the pattern used to parse the date of the dump of the files/directories
    listed..
    '''
    site = rse.split('_')[0]
    if site not in config.sections():
        base_url = ddmendpoint_url(rse) + 'dumps'
        url_pattern = 'dump_%Y%m%d'
    else:
        url_components = config.get(site, rse).split('/')
        # The pattern may not be the last component
        pattern_index = next(idx for idx, comp in enumerate(url_components) if '%m' in comp)
        base_url = '/'.join(url_components[:pattern_index])
        url_pattern = '/'.join(url_components[pattern_index:])

    return base_url, url_pattern 
Example #8
Source File: system_info.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()
        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #9
Source File: myconfig.py    From genmon with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, filename = None, section = None, simulation = False, log = None):

        super(MyConfig, self).__init__()
        self.log = log
        self.FileName = filename
        self.Section = section
        self.Simulation = simulation
        self.CriticalLock = threading.Lock()        # Critical Lock (writing conf file)
        self.InitComplete = False
        try:
            self.config = RawConfigParser()
            self.config.read(self.FileName)

            if self.Section == None:
                SectionList = self.GetSections()
                if len(SectionList):
                    self.Section = SectionList[0]

        except Exception as e1:
            self.LogErrorLine("Error in MyConfig:init: " + str(e1))
            return
        self.InitComplete = True
    #---------------------MyConfig::HasOption----------------------------------- 
Example #10
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #11
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #12
Source File: pluginstore.py    From xuebao with MIT License 6 votes vote down vote up
def parse_info_file(infofile_path):
    logger = logging.getLogger(__name__)
    cp = configparser.RawConfigParser()
    cp.read(infofile_path)

    options_missing = False
    for option in MANDATORY_OPTIONS:
        if not cp.has_option(*option):
            options_missing = True
            logger.debug("Plugin info file '%s' missing value '%s'", infofile_path, option)
    
    if options_missing:
        raise PluginError("Info file is missing values!")
    
    logger.debug("Plugin info file '%s' parsed successfully!", infofile_path)
    return cp 
Example #13
Source File: system_info.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #14
Source File: config.py    From QMusic with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, config_file, default_config=None):
        '''
        Init config module.

        @param config_file: Config filepath.
        @param default_config: Default config value use when config file is empty.
        '''
        gobject.GObject.__init__(self)
        self.config_parser = ConfigParser()
        self.remove_option = self.config_parser.remove_option
        self.has_option = self.config_parser.has_option
        self.add_section = self.config_parser.add_section
        self.getboolean = self.config_parser.getboolean
        self.getint = self.config_parser.getint
        self.getfloat = self.config_parser.getfloat
        self.options = self.config_parser.options
        self.items = self.config_parser.items
        self.config_file = config_file
        self.default_config = default_config

        # Load default configure.
        self.load_default() 
Example #15
Source File: frontend.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def read(self, filenames, option_parser):
        if type(filenames) in (str, unicode):
            filenames = [filenames]
        for filename in filenames:
            try:
                # Config files must be UTF-8-encoded:
                fp = codecs.open(filename, 'r', 'utf-8')
            except IOError:
                continue
            try:
                if sys.version_info < (3,2):
                    CP.RawConfigParser.readfp(self, fp, filename)
                else:
                    CP.RawConfigParser.read_file(self, fp, filename)
            except UnicodeDecodeError:
                self._stderr.write(self.not_utf8_error % (filename, filename))
                fp.close()
                continue
            fp.close()
            self._files.append(filename)
            if self.has_section('options'):
                self.handle_old_config(filename)
            self.validate_settings(filename, option_parser) 
Example #16
Source File: plugin_loader.py    From vt-ida-plugin with Apache License 2.0 6 votes vote down vote up
def read_config(self):
    """Read the user's configuration file."""

    logging.debug('[VT Plugin] Reading user config file: %s', self.vt_cfgfile)
    config_file = configparser.RawConfigParser()
    config_file.read(self.vt_cfgfile)

    try:
      if config_file.get('General', 'auto_upload') == 'True':
        self.auto_upload = True
      else:
        self.auto_upload = False
      return True
    except:
      logging.error('[VT Plugin] Error reading the user config file.')
      return False 
Example #17
Source File: optionfile.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        kwargs['allow_no_value'] = True
        configparser.RawConfigParser.__init__(self, **kwargs) 
Example #18
Source File: rotate.py    From awsudo with MIT License 5 votes vote down vote up
def __init__(self,
                 section,
                 filename=path.expanduser('~/.aws/credentials')):
        self._filename = filename
        self._config = RawConfigParser()
        self.section = section

        with open(self._filename, 'r') as f:
            self._config.readfp(f)

        if not self._config.has_section(section):
            raise SystemExit('could not find section [%s] in %r'
                             % (section, filename)) 
Example #19
Source File: optionfile.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        kwargs['allow_no_value'] = True
        configparser.RawConfigParser.__init__(self, **kwargs) 
Example #20
Source File: mysql2influx.py    From Mysql-to-influxdb with MIT License 5 votes vote down vote up
def main():
    #Argument parsing
    parser = argparse.ArgumentParser(description = 'Get Time series data from MYSQL and push it to influxdb' )

    parser.add_argument( '-d', '--debug', help = 'set logging level to debug', action = 'store_true')
    parser.add_argument( '-c', '--config', help = 'config file location', nargs = 1, default = 'settings.ini' )
    parser.add_argument( '-s', '--server', help = 'run as server with interval ',action = 'store_true' )

    args = parser.parse_args()


    # Init logging
    logging.basicConfig(level=(logging.DEBUG if True or args.debug else logging.INFO))

    logger.debug('Starting up with config file  %s' % (args.config))
    #get config file
    config = RawConfigParser()
    config.read(args.config)

    _sleep_time = float(config.get('server','interval'))

    logger.debug('configs  %s' % (config.sections()))
    #start
    mclient = Mysql2Influx(config)
    if not args.server:
        mclient.transfer_data()
    else:
        logger.info('Starting up server mode interval:  %s' % _sleep_time)
        while True:
            try:
                mclient.transfer_data()
            except Exception,e:
                logger.exception("Error occured will try again")
            time.sleep(_sleep_time)
            mclient.initialise_database() 
Example #21
Source File: optionfile.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get(self, section, option):
        value = configparser.RawConfigParser.get(self, section, option)
        return self.__remove_quotes(value) 
Example #22
Source File: test_cfgparser.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_none_as_value_stringified_raw(self):
        output = self.prepare(ConfigParser.RawConfigParser)
        self.assertEqual(output, self.expected_output) 
Example #23
Source File: config.py    From Computable with MIT License 5 votes vote down vote up
def _readFromFilenames(self, filenames):
        config = []
        for filename in filenames:
            cfg = ConfigParser.RawConfigParser()
            try:
                cfg.read(filename)
            except ConfigParser.Error, exc:
                raise ConfigError("Error reading config file %r: %s" %
                                  (filename, str(exc)))
            config.extend(self._configTuples(cfg, filename)) 
Example #24
Source File: npy_pkg_config.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def parse_config(filename, dirs=None):
    if dirs:
        filenames = [os.path.join(d, filename) for d in dirs]
    else:
        filenames = [filename]

    config = RawConfigParser()

    n = config.read(filenames)
    if not len(n) >= 1:
        raise PkgNotFound("Could not find file(s) %s" % str(filenames))

    # Parse meta and variables sections
    meta = parse_meta(config)

    vars = {}
    if config.has_section('variables'):
        for name, value in config.items("variables"):
            vars[name] = _escape_backslash(value)

    # Parse "normal" sections
    secs = [s for s in config.sections() if not s in ['meta', 'variables']]
    sections = {}

    requires = {}
    for s in secs:
        d = {}
        if config.has_option(s, "requires"):
            requires[s] = config.get(s, 'requires')

        for name, value in config.items(s):
            d[name] = value
        sections[s] = d

    return meta, vars, sections, requires 
Example #25
Source File: test_cfgparser.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_none_as_value_stringified_raw(self):
        output = self.prepare(ConfigParser.RawConfigParser)
        self.assertEqual(output, self.expected_output) 
Example #26
Source File: configure_conf_file.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def modify_conf_file():
    try:
        variables_list = json.loads(args.variables_list)
        conf_list = []
        conf_file = open('{}sources/infrastructure-provisioning/src/general/conf/dlab.ini'.format(args.dlab_dir), 'r')
        for line in conf_file:
            conf_list.append(line)

        for line in conf_list:
            if line[0:2] == '# ':
                conf_list[conf_list.index(line)] = line.replace('# ', '')

        with open('/tmp/dlab.ini.modified', 'w') as conf_file_modified:
            conf_file_modified.writelines(conf_list)

        config = ConfigParser.RawConfigParser()
        config.read('/tmp/dlab.ini.modified')
        for section in config.sections():
            options = config.options(section)
            for option in options:
                try:
                    print('Trying to put variable {}_{} to conf file'.format(section, option))
                    config.set(section, option, variables_list['{}_{}'.format(section, option)])
                except:
                    print('Such variable doesn`t exist!')
                    config.remove_option(section, option)

        with open('{}sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(args.dlab_dir), 'w') as conf_file_final:
            config.write(conf_file_final)
    except Exception as error:
        print('Error with modifying conf files:')
        print(str(error))
        sys.exit(1) 
Example #27
Source File: __init__.py    From aws-mfa with MIT License 5 votes vote down vote up
def get_config(aws_creds_path):
    config = configparser.RawConfigParser()
    try:
        config.read(aws_creds_path)
    except configparser.ParsingError:
        e = sys.exc_info()[1]
        log_error_and_exit(logger, "There was a problem reading or parsing "
                           "your credentials file: %s" % (e.args[0],))
    return config 
Example #28
Source File: gpl.plugin.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file_path="config"):
        try:
            import ConfigParser
            self.__configParser = ConfigParser.RawConfigParser()
            self.__configParser.read(file_path)

        except ImportError as ie:
            raise Exception("ConfigParser module not available. Please install")

        except Exception as e:
            raise Exception("Error parsing " + file_path + ": " + str(e)) 
Example #29
Source File: config.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file_path="config"):
        try:
            import ConfigParser
            self.__configParser = ConfigParser.RawConfigParser()
            self.__configParser.read(file_path)

        except ImportError as ie:
            raise Exception("ConfigParser module not available. Please install")

        except Exception as e:
            raise Exception("Error parsing " + file_path + ": " + str(e)) 
Example #30
Source File: config.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file_path="config"):
        try:
            import ConfigParser
            self.__configParser = ConfigParser.RawConfigParser()
            self.__configParser.read(file_path)

        except ImportError as ie:
            raise Exception("ConfigParser module not available. Please install")

        except Exception as e:
            raise Exception("Error parsing " + file_path + ": " + str(e))