當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。