python类strtobool()的实例源码

_bool.py 文件源码 项目:typepy 作者: thombashi 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __strict_strtobool(value):
        from distutils.util import strtobool

        if isinstance(value, bool):
            return value

        try:
            lower_text = value.lower()
        except AttributeError:
            raise ValueError("invalid value '{}'".format(str(value)))

        binary_value = strtobool(lower_text)
        if lower_text not in ["true", "false"]:
            raise ValueError("invalid value '{}'".format(str(value)))

        return bool(binary_value)
validators.py 文件源码 项目:routersploit 作者: reverse-shell 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def boolify(value):
    """ Function that will translate common strings into bool values

    True -> "True", "t", "yes", "y", "on", "1"
    False -> any other string

    Objects other than string will be transformed
    using built-in bool() function.
    """
    if isinstance(value, basestring):
        try:
            return bool(strtobool(value))
        except ValueError:
            return False
    else:
        return bool(value)
validators.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def boolify(value):
    """ Function that will translate common strings into bool values

    True -> "True", "t", "yes", "y", "on", "1"
    False -> any other string

    Objects other than string will be transformed
    using built-in bool() function.
    """
    if isinstance(value, basestring):
        try:
            return bool(strtobool(value))
        except ValueError:
            return False
    else:
        return bool(value)
audit.py 文件源码 项目:microcosm-flask 作者: globality-corp 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def logging_levels():
    """
    Context manager to conditionally set logging levels.

    Supports setting per-request debug logging using the `X-Request-Debug` header.

    """
    enabled = strtobool(request.headers.get("x-request-debug", "false"))
    level = None
    try:
        if enabled:
            level = getLogger().getEffectiveLevel()
            getLogger().setLevel(DEBUG)
        yield
    finally:
        if enabled:
            getLogger().setLevel(level)
ves_app.py 文件源码 项目:barometer 作者: opnfv 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def config(self, config):
        """VES option configuration"""
        for key, value in config.items('config'):
            if key in self._app_config:
                try:
                    if type(self._app_config[key]) == int:
                        value = int(value)
                    elif type(self._app_config[key]) == float:
                        value = float(value)
                    elif type(self._app_config[key]) == bool:
                        value = bool(strtobool(value))

                    if isinstance(value, type(self._app_config[key])):
                        self._app_config[key] = value
                    else:
                        logging.error("Type mismatch with %s" % key)
                        sys.exit()
                except ValueError:
                    logging.error("Incorrect value type for %s" % key)
                    sys.exit()
            else:
                logging.error("Incorrect key configuration %s" % key)
                sys.exit()
artefacts.py 文件源码 项目:gtool 作者: gtoolframework 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, obj, config=None):

        _config = {FILEONLY: False}

        if config is not None:
            _configlist = [c.strip().lower() for c in config.split('=')]

            if len(_configlist) == 2 and _configlist[0] == FILEONLY:
                _config[FILEONLY] = strtobool(_configlist[1])
            else:
                raise ValueError('Artefact method plugin (used in user defined class %s) accepts a single argument of either '
                                 '"fileonly = True" or "fileonly = False". By default fileonly mode is False '
                                 'and does not need to be specified' % striptoclassname(type(obj)))

        super(Artefacts, self).__init__(obj, config=_config)

        self.computable = True
menu.py 文件源码 项目:jvcprojectortools 作者: arvehj 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main():
    """JVC Projector tools main menu"""
    while True:
        try:
            Menu()
            break
        except Exception as err:
            if isinstance(err, ExceptionInThread):
                err, exc = err.args
            else:
                exc = sys.exc_info()
            print(err)
            try:
                if strtobool(input('error occured print stack trace? ')):
                    traceback.print_exception(*exc)
            except:
                pass
            try:
                if not strtobool(input('restart? ')):
                    break
            except:
                break
util.py 文件源码 项目:deb-python-rjsmin 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def humanbool(name, value):
    """
    Determine human boolean value

    :Parameters:
      `name` : ``str``
        The config key (used for error message)

      `value` : ``str``
        The config value

    :Return: The boolean value
    :Rtype: ``bool``

    :Exceptions:
      - `ValueError` : The value could not be recognized
    """
    try:
        return _util.strtobool(str(value).strip().lower() or 'no')
    except ValueError:
        raise ValueError("Unrecognized config value: %s = %s" % (name, value))
util.py 文件源码 项目:deb-python-rjsmin 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def humanbool(name, value):
    """
    Determine human boolean value

    :Parameters:
      `name` : ``str``
        The config key (used for error message)

      `value` : ``str``
        The config value

    :Return: The boolean value
    :Rtype: ``bool``

    :Exceptions:
      - `ValueError` : The value could not be recognized
    """
    try:
        return _util.strtobool(str(value).strip().lower() or 'no')
    except ValueError:
        raise ValueError("Unrecognized config value: %s = %s" % (name, value))
util.py 文件源码 项目:deb-python-rcssmin 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def humanbool(name, value):
    """
    Determine human boolean value

    :Parameters:
      `name` : ``str``
        The config key (used for error message)

      `value` : ``str``
        The config value

    :Return: The boolean value
    :Rtype: ``bool``

    :Exceptions:
      - `ValueError` : The value could not be recognized
    """
    try:
        return _util.strtobool(str(value).strip().lower() or 'no')
    except ValueError:
        raise ValueError("Unrecognized config value: %s = %s" % (name, value))
util.py 文件源码 项目:deb-python-rcssmin 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def humanbool(name, value):
    """
    Determine human boolean value

    :Parameters:
      `name` : ``str``
        The config key (used for error message)

      `value` : ``str``
        The config value

    :Return: The boolean value
    :Rtype: ``bool``

    :Exceptions:
      - `ValueError` : The value could not be recognized
    """
    try:
        return _util.strtobool(str(value).strip().lower() or 'no')
    except ValueError:
        raise ValueError("Unrecognized config value: %s = %s" % (name, value))
analyzer.py 文件源码 项目:toll_road 作者: idosekely 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _str_to_bool(self, val):
        try:
            return bool(strtobool(val))
        except ValueError:
            return None
baseparser.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 53 收藏 0 点赞 0 评论 0
def update_defaults(self, defaults):
        """Updates the given defaults with values from the config files and
        the environ. Does a little special handling for certain types of
        options (lists)."""
        # Then go and look for the other sources of configuration:
        config = {}
        # 1. config files
        for section in ('global', self.name):
            config.update(self.normalize_keys(self.get_config_section(section)))
        # 2. environmental variables
        config.update(self.normalize_keys(self.get_environ_vars()))
        # Then set the options with those values
        for key, val in config.items():
            option = self.get_option(key)
            if option is not None:
                # ignore empty values
                if not val:
                    continue
                if option.action in ('store_true', 'store_false', 'count'):
                    val = strtobool(val)
                if option.action == 'append':
                    val = val.split()
                    val = [self.check_default(option, key, v) for v in val]
                else:
                    val = self.check_default(option, key, val)

                defaults[option.dest] = val
        return defaults
__init__.py 文件源码 项目:routersploit 作者: reverse-shell 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def boolify(value):
    """ Function that will translate common strings into bool values

    True -> "True", "t", "yes", "y", "on", "1"
    False -> any other string

    Objects other than string will be transformed using built-in bool() function.
    """
    if isinstance(value, basestring):
        try:
            return bool(strtobool(value))
        except ValueError:
            return False
    else:
        return bool(value)
baseparser.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def update_defaults(self, defaults):
        """Updates the given defaults with values from the config files and
        the environ. Does a little special handling for certain types of
        options (lists)."""
        # Then go and look for the other sources of configuration:
        config = {}
        # 1. config files
        for section in ('global', self.name):
            config.update(self.normalize_keys(self.get_config_section(section)))
        # 2. environmental variables
        config.update(self.normalize_keys(self.get_environ_vars()))
        # Then set the options with those values
        for key, val in config.items():
            option = self.get_option(key)
            if option is not None:
                # ignore empty values
                if not val:
                    continue
                if option.action in ('store_true', 'store_false', 'count'):
                    val = strtobool(val)
                if option.action == 'append':
                    val = val.split()
                    val = [self.check_default(option, key, v) for v in val]
                else:
                    val = self.check_default(option, key, val)

                defaults[option.dest] = val
        return defaults
__init__.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def boolify(value):
    """ Function that will translate common strings into bool values

    True -> "True", "t", "yes", "y", "on", "1"
    False -> any other string

    Objects other than string will be transformed using built-in bool() function.
    """
    if isinstance(value, basestring):
        try:
            return bool(strtobool(value))
        except ValueError:
            return False
    else:
        return bool(value)
audit.py 文件源码 项目:microcosm-flask 作者: globality-corp 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def should_skip_logging(func):
    """
    Should we skip logging for this handler?

    """
    disabled = strtobool(request.headers.get("x-request-nolog", "false"))
    return disabled or getattr(func, SKIP_LOGGING, False)
audit.py 文件源码 项目:microcosm-flask 作者: globality-corp 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def configure_audit_decorator(graph):
    """
    Configure the audit decorator.

    Example Usage:

        @graph.audit
        def login(username, password):
            ...
    """
    include_request_body = int(graph.config.audit.include_request_body)
    include_response_body = int(graph.config.audit.include_response_body)
    include_path = strtobool(graph.config.audit.include_path)
    include_query_string = strtobool(graph.config.audit.include_query_string)

    def _audit(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            options = AuditOptions(
                include_request_body=include_request_body,
                include_response_body=include_response_body,
                include_path=include_path,
                include_query_string=include_query_string,
            )
            return _audit_request(options, func, graph.request_context, *args, **kwargs)
        return wrapper
    return _audit
utils.py 文件源码 项目:gennotes 作者: madprime 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def to_bool(env, default='false'):
    """
    Convert a string to a bool.
    """
    return bool(util.strtobool(os.getenv(env, default)))
os_utils.py 文件源码 项目:monitorstack 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, os_auth_args):
        """Initialization method for class.

        :param os_auth_args: dict containing auth creds.
        :type os_auth_args: dict
        """
        self.os_auth_args = os_auth_args
        insecure = bool(strtobool(self.os_auth_args.get('insecure', 'False')))
        self.verify = insecure is False
__init__.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def str2bool(s):
    if is_string(s):
        return strtobool(s)
    return bool(s)
config.py 文件源码 项目:dataScryer 作者: Griesbacher 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, file):
        if python_3():
            self.__settings = configparser.ConfigParser()
        else:
            self.__settings = ConfigParser.SafeConfigParser()
        try:
            with open(file) as f:
                self.__settings.readfp(f)
        except IOError as e:
            raise ConfigfileException(e)

        # Main
        self.data['main'] = {'customMethods': self.__settings.get('Main', 'Custom_Methods'),
                             'log_level': self.__settings.get('Main', 'Log_Level'),
                             'daemon': strtobool(self.__settings.get('Main', 'Daemon')),
                             'update_rate': int(self.__settings.get('Main', 'Config_Updaterate_in_Minutes')) * 60,
                             'log_performance': strtobool(self.__settings.get('Main', 'Log_Performance'))}

        # Livestatus
        livestatus_split = self.__settings.get('Livestatus', 'Address').split(":")
        self.data['livestatus'] = {'protocol': livestatus_split[0], 'address': livestatus_split[1]}
        if len(livestatus_split) == 3:
            self.data['livestatus']['port'] = int(livestatus_split[2])

        # Histou
        # self.data['histou'] = {'prot': "http", 'address': self.__settings.get('Histou', 'Address')}
        histou_split = self.__settings.get('Histou', 'Address').split(":", 1)
        self.data['histou'] = {'prot': histou_split[0], 'address': histou_split[1]}
        self.data['histou']['user'] = self.__settings.get('Histou', 'User')
        self.data['histou']['password'] = self.__settings.get('Histou', 'Password')

        # Influxdb
        self.data['influxdb'] = {'read': {'address': self.__settings.get('InfluxDB', 'Address_Read'),
                                          'db': self.__settings.get('InfluxDB', 'DB_Read'),
                                          'args': self.__settings.get('InfluxDB', 'DB_Read_Args')},
                                 'write': {'address': self.__settings.get('InfluxDB', 'Address_Write'),
                                           'db_forecast': self.__settings.get('InfluxDB', 'DB_Write_Forecast'),
                                           'db_anomaly': self.__settings.get('InfluxDB', 'DB_Write_Anomaly'),
                                           'args': self.__settings.get('InfluxDB', 'DB_Write_Args')}}
directedgraph.py 文件源码 项目:gtool 作者: gtoolframework 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self):

        _scheme = runtimenamespace().get('outputscheme', None)
        if _scheme is None:
            raise ValueError('Output scheme is not defined')

        _outputconfig = partialnamespace('output').get(_scheme, None)
        if _outputconfig is None:
            raise ValueError('Output scheme configuration was not retrieved')

        _autolink = _outputconfig.get('autolink', None)
        if _autolink is not None:
            self.autolink = strtobool(_autolink)
        else:
            self.autolink = True

        _linkattribute = _outputconfig.get('link', None)
        if _linkattribute is None and not self.autolink:
            raise ValueError('a "link:" value must be set in [output.%s] '
                             'in gtool.cfg when using directedgraph output '
                             'and autolink is disabled' % _scheme)
        self.linkattribute = _linkattribute

        _linkproperties = _outputconfig.get('linkprops', None)
        if _linkproperties is not None:
            self.linkproperties = [l.strip() for l in _linkproperties.split(',')]
        else:
            self.linkproperties = []




        super(Directedgraph, self).__init__()
url.py 文件源码 项目:gtool 作者: gtoolframework 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __validate__(self, valuedict):
        _public = valuedict.get('public', None)
        if _public is None:
            public = 0 # False
        else:
            public = strtobool('%s' % _public)
            warnings.warn('public check does not currently work due a problem in the underlying validators library')
        try:
            url(self.__value__, public=public) # TODO public / private test doesn't work
        except ValidationFailure:
            raise ValueError('Was expecting a valid %s but got %s' % ('public URL' if public else 'URL', len(self.__value__)))
        return True
url.py 文件源码 项目:gtool 作者: gtoolframework 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def __validate__(self, valuedict):
        _public = valuedict.get('public', None)
        if _public is None:
            public = 0 # False
        else:
            public = strtobool('%s' % _public)
            warnings.warn('public check does not currently work due a problem in the underlying validators library')
        try:
            url(self.__value__, public=public) # TODO public / private test doesn't work
        except ValidationFailure:
            raise ValueError('Was expecting a valid %s but got %s' % ('public URL' if public else 'URL', len(self.__value__)))
        return True
settings.py 文件源码 项目:ceph-backup 作者: teralytics 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def start_backup(self):
        '''
        Read settings and starts backup
        '''
        for section in self._config.sections():
            # Run a backup for each section
            print "Starting backup for pool {}".format(section)
            images = self.getsetting(section, 'images').split(',')
            backup_dest = self.getsetting(section, 'destination directory')
            conf_file = self.getsetting(section, 'ceph config')
            check_mode = bool(strtobool(self.getsetting(section, 'check mode')))
            compress_mode = bool(strtobool(self.getsetting(section, 'compress')))
            window_size = int(self.getsetting(section, 'window size'))
            window_unit = self.getsetting(section, 'window unit')
            backup_mode = self.getsetting(section, 'backup mode')
            cb = CephFullBackup(section, images, backup_dest, conf_file, check_mode, compress_mode, window_size, window_unit)
            if backup_mode == 'full':
                print "Full ceph backup"
                cb.print_overview()
                cb.full_backup()
            elif backup_mode == 'incremental':
                print "Incremental ceph backup"
                cb.print_overview()
                cb.incremental_backup()
            else:
                raise Exception("Unknown backup mode: {}".format(backup_mode))
baseparser.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def update_defaults(self, defaults):
        """Updates the given defaults with values from the config files and
        the environ. Does a little special handling for certain types of
        options (lists)."""
        # Then go and look for the other sources of configuration:
        config = {}
        # 1. config files
        for section in ('global', self.name):
            config.update(self.normalize_keys(self.get_config_section(section)))
        # 2. environmental variables
        config.update(self.normalize_keys(self.get_environ_vars()))
        # Then set the options with those values
        for key, val in config.items():
            option = self.get_option(key)
            if option is not None:
                # ignore empty values
                if not val:
                    continue
                if option.action in ('store_true', 'store_false', 'count'):
                    val = strtobool(val)
                if option.action == 'append':
                    val = val.split()
                    val = [self.check_default(option, key, v) for v in val]
                else:
                    val = self.check_default(option, key, val)

                defaults[option.dest] = val
        return defaults
test_frontend.py 文件源码 项目:callisto-core 作者: project-callisto 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def headless_mode():
    return not strtobool(os.environ.get('HEADED', 'False'))
tenant_api.py 文件源码 项目:callisto-core 作者: project-callisto 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def cast_string_to_type(
    value: str,
    cast: [str, bool, int]
) -> [str, bool, int]:
    if cast is str:
        return value
    elif cast is bool:
        return strtobool(value)
    elif cast is int:
        return int(value)
    else:
        raise KeyError('Invalid `cast` param')
proposal.py 文件源码 项目:focal-loss 作者: unsky 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, feat_stride='16', scales='(8, 16, 32)', ratios='(0.5, 1, 2)', output_score='False',
                 rpn_pre_nms_top_n='6000', rpn_post_nms_top_n='300', threshold='0.3', rpn_min_size='16'):
        super(ProposalProp, self).__init__(need_top_grad=False)
        self._feat_stride = int(feat_stride)
        self._scales = scales
        self._ratios = ratios
        self._output_score = strtobool(output_score)
        self._rpn_pre_nms_top_n = int(rpn_pre_nms_top_n)
        self._rpn_post_nms_top_n = int(rpn_post_nms_top_n)
        self._threshold = float(threshold)
        self._rpn_min_size = int(rpn_min_size)


问题


面经


文章

微信
公众号

扫码关注公众号