当前位置: 首页>>代码示例>>Python>>正文


Python configparser.NoOptionError方法代码示例

本文整理汇总了Python中configparser.NoOptionError方法的典型用法代码示例。如果您正苦于以下问题:Python configparser.NoOptionError方法的具体用法?Python configparser.NoOptionError怎么用?Python configparser.NoOptionError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在configparser的用法示例。


在下文中一共展示了configparser.NoOptionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_key

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
开发者ID:rtshome,项目名称:pgrepup,代码行数:22,代码来源:crypt.py

示例2: __add_checks__

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def __add_checks__(self, appconfig, result):
        checks = []
        unwanted = []
        for checker in appconfig.sections():
            if "checker" in checker.lower() or "collector" in checker.lower():
                try: 
                    enabled=not strtobool(appconfig.get(checker, 'disabled'))
                except NoOptionError:
                    enabled=True
                try: 
                    enabled=strtobool(appconfig.get(checker, 'enabled'))
                except NoOptionError:
                    enabled=True
                if enabled:
                    checks.append(checker)
                else:
                    unwanted.append(checker)
        result['checks'] = checks
        result['unwanted'] = unwanted 
开发者ID:koenbuyens,项目名称:securityheaders,代码行数:21,代码来源:optionparser.py

示例3: get_config_from_root

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def get_config_from_root(root):
    # 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")
    cfg.parentdir_prefix = get(parser, "parentdir_prefix")
    cfg.verbose = get(parser, "verbose")
    return cfg 
开发者ID:menpo,项目名称:landmarkerio-server,代码行数:26,代码来源:versioneer.py

示例4: get

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def get(self, conf, stanza, option):
        '''Return the metadata value of option in [conf/stanza] section.

        :param conf: Conf name.
        :type conf: ``string``
        :param stanza: Stanza name.
        :type stanza: ``string``
        :param option: Option name in section [conf/stanza].
        :type option: ``string``
        :returns: Value of option in section [conf/stanza].
        :rtype: ``string``

        :raises ValueError: Raises ValueError if the value cannot be determined.
            Note that this can occur in several situations:

        - The section does not exist.
        - The section exists but the option does not exist.
        '''

        try:
            return self._cfg.get('/'.join([conf, stanza]), option)
        except (NoSectionError, NoOptionError):
            raise ValueError('The metadata value could not be determined.') 
开发者ID:remg427,项目名称:misp42splunk,代码行数:25,代码来源:metadata.py

示例5: get_float

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def get_float(self, conf, stanza, option):
        '''Return the metadata value of option in [conf/stanza] section as a float.

        :param conf: Conf name.
        :type conf: ``string``
        :param stanza: Stanza name.
        :type stanza: ``string``
        :param option: Option name in section [conf/stanza].
        :type option: ``string``
        :returns: A float value.
        :rtype: ``float``

        :raises ValueError: Raises ValueError if the value cannot be determined.
            Note that this can occur in several situations:

        - The stanza exists but the value does not exist (perhaps having never
          been updated).
        - The stanza does not exist.
        - The value exists but cannot be converted to a float.
        '''

        try:
            return self._cfg.getfloat('/'.join([conf, stanza]), option)
        except (NoSectionError, NoOptionError):
            raise ValueError('The metadata value could not be determined.') 
开发者ID:remg427,项目名称:misp42splunk,代码行数:27,代码来源:metadata.py

示例6: _read_default_settings

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def _read_default_settings():
        cur_dir = op.dirname(op.abspath(__file__))
        setting_file = op.join(cur_dir,"../../","splunktalib", "setting.conf")
        parser = configparser.ConfigParser()
        parser.read(setting_file)
        settings = {}
        keys = ("process_size", "thread_min_size", "thread_max_size",
                "task_queue_size")
        for option in keys:
            try:
                settings[option] = parser.get("global", option)
            except configparser.NoOptionError:
                settings[option] = -1

            try:
                settings[option] = int(settings[option])
            except ValueError:
                settings[option] = -1
        log.logger.debug("settings: %s", settings)
        return settings 
开发者ID:remg427,项目名称:misp42splunk,代码行数:22,代码来源:ta_data_loader.py

示例7: match_properties

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def match_properties(self, match, properties):
        '''
        Call this when the recursive search has been done to analyze the results
        and understand which properties have been spotted.

        match: returned by droidutil.recursive_search. This is a dictionary
        of matching lines ordered by matching keyword (pattern)

        properties: dictionary of properties where the key is the property name
        and the value will be False/True if set or not
        
        throws NoSessionError, NoOptionError
        '''
        for section in self.configparser.sections():
            pattern_list = self.configparser.get(section, 'pattern').split('|')
            properties[section] = False
            for pattern in pattern_list:
                if match[pattern]:
                    if self.verbose:
                        print( "Setting properties[%s] = True (matches %s)" % (section, pattern))
                    properties[section] = True
                    break 
开发者ID:cryptax,项目名称:droidlysis,代码行数:24,代码来源:droidconfig.py

示例8: get_loader

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def get_loader(self):
        paths = [os.path.join(self.cache_dir, phase + '.pkl') for phase in self.config.get('eval', 'phase').split()]
        dataset = utils.data.Dataset(utils.data.load_pickles(paths))
        logging.info('num_examples=%d' % len(dataset))
        size = tuple(map(int, self.config.get('image', 'size').split()))
        try:
            workers = self.config.getint('data', 'workers')
        except configparser.NoOptionError:
            workers = multiprocessing.cpu_count()
        collate_fn = utils.data.Collate(
            transform.parse_transform(self.config, self.config.get('transform', 'resize_eval')),
            [size],
            transform_image=transform.get_transform(self.config, self.config.get('transform', 'image_test').split()),
            transform_tensor=transform.get_transform(self.config, self.config.get('transform', 'tensor').split()),
        )
        return torch.utils.data.DataLoader(dataset, batch_size=self.args.batch_size, num_workers=workers, collate_fn=collate_fn) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:18,代码来源:eval.py

示例9: __init__

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def __init__(self, env):
        super(SummaryWorker, self).__init__()
        self.env = env
        self.config = env.config
        self.queue = multiprocessing.Queue()
        try:
            self.timer_scalar = utils.train.Timer(env.config.getfloat('summary', 'scalar'))
        except configparser.NoOptionError:
            self.timer_scalar = lambda: False
        try:
            self.timer_image = utils.train.Timer(env.config.getfloat('summary', 'image'))
        except configparser.NoOptionError:
            self.timer_image = lambda: False
        try:
            self.timer_histogram = utils.train.Timer(env.config.getfloat('summary', 'histogram'))
        except configparser.NoOptionError:
            self.timer_histogram = lambda: False
        with open(os.path.expanduser(os.path.expandvars(env.config.get('summary_histogram', 'parameters'))), 'r') as f:
            self.histogram_parameters = utils.RegexList([line.rstrip() for line in f])
        self.draw_bbox = utils.visualize.DrawBBox(env.category)
        self.draw_feature = utils.visualize.DrawFeature() 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:23,代码来源:train.py

示例10: get_loader

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def get_loader(self):
        paths = [os.path.join(self.cache_dir, phase + '.pkl') for phase in self.config.get('train', 'phase').split()]
        dataset = utils.data.Dataset(
            utils.data.load_pickles(paths),
            transform=transform.augmentation.get_transform(self.config, self.config.get('transform', 'augmentation').split()),
            one_hot=None if self.config.getboolean('train', 'cross_entropy') else len(self.category),
            shuffle=self.config.getboolean('data', 'shuffle'),
            dir=os.path.join(self.model_dir, 'exception'),
        )
        logging.info('num_examples=%d' % len(dataset))
        try:
            workers = self.config.getint('data', 'workers')
            if torch.cuda.is_available():
                workers = workers * torch.cuda.device_count()
        except configparser.NoOptionError:
            workers = multiprocessing.cpu_count()
        collate_fn = utils.data.Collate(
            transform.parse_transform(self.config, self.config.get('transform', 'resize_train')),
            utils.train.load_sizes(self.config),
            maintain=self.config.getint('data', 'maintain'),
            transform_image=transform.get_transform(self.config, self.config.get('transform', 'image_train').split()),
            transform_tensor=transform.get_transform(self.config, self.config.get('transform', 'tensor').split()),
            dir=os.path.join(self.model_dir, 'exception'),
        )
        return torch.utils.data.DataLoader(dataset, batch_size=self.args.batch_size * torch.cuda.device_count() if torch.cuda.is_available() else self.args.batch_size, shuffle=True, num_workers=workers, collate_fn=collate_fn, pin_memory=torch.cuda.is_available()) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:27,代码来源:train.py

示例11: iterate

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def iterate(self, data):
        for key in data:
            t = data[key]
            if torch.is_tensor(t):
                data[key] = utils.ensure_device(t)
        tensor = torch.autograd.Variable(data['tensor'])
        pred = pybenchmark.profile('inference')(model._inference)(self.inference, tensor)
        height, width = data['image'].size()[1:3]
        rows, cols = pred['feature'].size()[-2:]
        loss, debug = pybenchmark.profile('loss')(model.loss)(self.anchors, norm_data(data, height, width, rows, cols), pred, self.config.getfloat('model', 'threshold'))
        loss_hparam = {key: loss[key] * self.config.getfloat('hparam', key) for key in loss}
        loss_total = sum(loss_hparam.values())
        self.optimizer.zero_grad()
        loss_total.backward()
        try:
            clip = self.config.getfloat('train', 'clip')
            nn.utils.clip_grad_norm(self.inference.parameters(), clip)
        except configparser.NoOptionError:
            pass
        self.optimizer.step()
        return dict(
            height=height, width=width, rows=rows, cols=cols,
            data=data, pred=pred, debug=debug,
            loss_total=loss_total, loss=loss, loss_hparam=loss_hparam,
        ) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:27,代码来源:train.py

示例12: __get_attr

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def __get_attr(cls, attr_type, section, option):
        """
        :param attr_type: can be int, float, str, bool
        :param section:
        :param option:
        :return:
        """
        result = None
        try:
            if attr_type is int:
                result = cls.Parser.getint(section=section, option=option)
            elif attr_type is float:
                result = cls.Parser.getfloat(section=section, option=option)
            elif attr_type is bool:
                result = cls.Parser.getfloat(section=section, option=option)
            elif attr_type is str:
                result = cls.Parser.getfloat(section=section, option=option)
        except configparser.NoOptionError:
            pass
        return result 
开发者ID:armor-ai,项目名称:IDEA,代码行数:22,代码来源:config.py

示例13: _module_init_

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def _module_init_(cls):
        """
        Initialize the class object on first module load.
        """
        cls.register(cls.__hash, "hash")
        cls.register(cls.__identity, "identity")
        cls.register(cls.__ligo, "ligo")
        cls.register(cls.__belleii, "belleii")
        policy_module = None
        try:
            policy_module = config.config_get('policy', 'lfn2pfn_module')
        except (NoOptionError, NoSectionError):
            pass
        if policy_module:
            # TODO: The import of importlib is done like this due to a dependency issue with python 2.6 and incompatibility of the module with py3.x
            # More information https://github.com/rucio/rucio/issues/875
            import importlib
            importlib.import_module(policy_module)

        cls._DEFAULT_LFN2PFN = config.get_lfn2pfn_algorithm_default() 
开发者ID:rucio,项目名称:rucio,代码行数:22,代码来源:protocol.py

示例14: config_get_bool

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def config_get_bool(section, option, raise_exception=True, default=None):
    """
    Return the boolean value for a given option in a section

    :param section: the named section.
    :param option: the named option.
    :param raise_exception: Boolean to raise or not NoOptionError or NoSectionError.
    :param default: the default value if not found.
.
    :returns: the configuration value.
    """
    try:
        return get_config().getboolean(section, option)
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as err:
        if raise_exception:
            raise err
        if default is None:
            return default
        return bool(default) 
开发者ID:rucio,项目名称:rucio,代码行数:21,代码来源:config.py

示例15: config_write

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import NoOptionError [as 别名]
def config_write(configfile, config, oldconfig):
    # Schreibt das Configfile
    # Ein Lock sollte im aufrufenden Programm gehalten werden!

    tmp_filename = get_random_filename(configfile)
    with codecs.open(tmp_filename, 'w', 'utf_8') as new_ini:
        for section_name in config.sections():
            new_ini.write(u'[{section_name}]\n'.format(section_name=section_name))
            for (key, value) in config.items(section_name):
                try:
                    new_ini.write(u'{key} = {value}\n'.format(key=key, value=update_settings(section_name, key, oldconfig.get(section_name, key))))
                except (configparser.NoSectionError, configparser.NoOptionError):
                    new_ini.write(u'{key} = {value}\n'.format(key=key, value=value))
            new_ini.write('\n')
        new_ini.flush()
        os.fsync(new_ini.fileno())
        new_ini.close()
        os.rename(tmp_filename, configfile) 
开发者ID:WLANThermo,项目名称:WLANThermo_v2,代码行数:20,代码来源:wlt_2_updateconfig.py


注:本文中的configparser.NoOptionError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。