我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.util.strtobool()。
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)
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)
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)
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()
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
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
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))
def _str_to_bool(self, val): try: return bool(strtobool(val)) except ValueError: return None
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
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)
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
def to_bool(env, default='false'): """ Convert a string to a bool. """ return bool(util.strtobool(os.getenv(env, default)))
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
def str2bool(s): if is_string(s): return strtobool(s) return bool(s)
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')}}
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__()
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
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))
def headless_mode(): return not strtobool(os.environ.get('HEADED', 'False'))
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')
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)
def extbool(value): """Bool or string with values ('0', '1', 'true', 'false', 'yes') to bool. """ if isinstance(value, bool): return value if isinstance(value, basestring): return bool(strtobool(value)) raise TypeError('Invalid type. Must be bool or string')
def prompt(query): """ Returns boolean for y/n input """ print '%s [y/n]: ' % query val = raw_input() try: ret = strtobool(val) except ValueError: print 'Reply with y/n' return prompt(query) return ret
def callapi(url, method='post', payload=None, headers=None, auth=None, check=True): """ Simple wrapper around `requests.post`, with excessive logging. Returns a Flask-friendly tuple on success or failure. Logs and re-raises any exceptions. """ if not headers: headers = {'Content-type': 'application/json'} try: logging.info("URL=%s" % url) logging.info("Auth=%s" % str(auth)) logging.info("Headers=%s" % headers) logging.info("Body=%s" % payload) logging.info("Check=%s" % check) if (auth is not None): r = requests.request(method, url, auth=auth, headers=headers, data=payload, verify=bool(strtobool(str(check)))) else: r = requests.request(method, url, headers=headers, data=payload, verify=check) if r.status_code >= 200 and r.status_code < 300: if (payload is None): return r.text else: return ("OK", r.status_code, None) except: logging.exception("Can't create new payload. Check code and try again.") raise return ("%s" % r.text, r.status_code, None)
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 config.update(dict(self.get_config_section('virtualenv'))) # 2. environmental variables config.update(dict(self.get_environ_vars())) # Then set the options with those values for key, val in config.items(): key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts option = self.get_option(key) if option is not None: # ignore empty values if not val: continue # handle multiline configs if option.action == 'append': val = val.split() else: option.nargs = 1 if option.action == 'store_false': val = not strtobool(val) elif option.action in ('store_true', 'count'): val = strtobool(val) try: val = option.convert_value(key, val) except optparse.OptionValueError: e = sys.exc_info()[1] print("An error occured during configuration: %s" % e) sys.exit(3) defaults[option.dest] = val return defaults
def confirm(prompt='Continue?\n', failure_prompt='User cancelled task'): ''' Prompt the user to continue. Repeat on unknown response. Raise ParseError on negative response ''' response = input(prompt) try: response_bool = strtobool(response) except ValueError: print('Unkown Response. Confirm with y, yes, t, true, on or 1; cancel with n, no, f, false, off or 0.') confirm(prompt, failure_prompt) if not response_bool: raise ParseError(failure_prompt)
def cli(main): # A decorator to add consistent CLI bootstrap # # Decorated function must accept argv and environ arguments and return an # exit code. # # The decorator adds basic logging setup and error management. The # decorated function can just raise exception and log using logging module # as usual. def cli_wrapper(argv=sys.argv[1:], environ=os.environ): debug = strtobool(environ.get('DEBUG', '0')) if debug: os.environ['TEMBOARD_LOGGING_LEVEL'] = b'DEBUG' retcode = 1 try: setup_logging(level='DEBUG' if debug else 'ERROR') logger.debug("Starting temBoard agent.") retcode = main(argv, environ) or 1 except KeyboardInterrupt: logger.info('Terminated.') except pdb.bdb.BdbQuit: logger.info("Graceful exit from debugger.") except UserError as e: retcode = e.retcode logger.critical("%s", e) except Exception: logger.exception('Unhandled error:') if debug: pdb.post_mortem(sys.exc_info()[2]) else: logger.error("This is a bug!") logger.error( "Please report traceback to " "https://github.com/dalibo/temboard-agent/issues! Thanks!" ) exit(retcode) return cli_wrapper
def boolean(raw): if raw in (True, False): return raw return bool(strtobool(raw))
def conf_load(self, conf): """Load configuration from dict""" conf = conf.copy() eotfname = conf.get('eotf') table = conf.get('table') highlight = conf.get('highlight') for eotfentry in eotf.eotfs: if eotfname == eotfentry.__name__: conf['eotf'] = eotfentry break else: if eotfname: print('not found eotf', eotfname) if table: conf['eotf'] = EOTFRaw else: conf.pop('eotf', None) if highlight: _, value = highlight.split('.') obj = Highlight.NONE for flag in value.split('|'): obj |= Highlight[flag] conf['highlight'] = obj for key, value in conf.items(): if hasattr(self, key): if self.debug: print('Import', key, value) setattr(self, key, value) else: print('Ignore unknown paramter', key, value) if not self.raw_gamma_table(): self.generate_table() if table is not None and table != self.table: if strtobool(input('Imported table does not match generated table\n' 'Use imported raw table instead (y/n)? ')): self.set_raw_table(table)
def write_jvc(self, jvc, verify=False): """Write gamma table to projector""" newgamma = self.get_table() if len(newgamma) != 3: newgamma = [newgamma, newgamma, newgamma] try: print('Picture mode:', jvc.get(Command.PictureMode).name) old_gamma_table = jvc.get(Command.GammaTable) print('Gamma Table:', old_gamma_table.name) if old_gamma_table not in {GammaTable.Custom1, GammaTable.Custom2, GammaTable.Custom3}: raise ValueError('Selected gamma table, {}, is not a custom gamma table'.format( old_gamma_table.name)) gamma_correction = jvc.get(Command.GammaCorrection) if gamma_correction is not GammaCorrection.Import: raise ValueError('Correction value for {} is not set to import, {}'.format( old_gamma_table.name, gamma_correction.name)) jvc.set(Command.GammaCorrection, GammaCorrection.Import) input_level_match = input_level = jvc.get(Command.HDMIInputLevel) if input_level_match is HDMIInputLevel.Auto: input_level_match = HDMIInputLevel.Standard if input_level_match != self.get_input_level(): raise ValueError('Projector input level, {}, ' 'does not match gamma curve input level, {}'.format( input_level.name, self.get_input_level().name)) except Exception as err: print('Failed to validate projector settings:', err) if not strtobool(input('Ignore and try to write table anyway (y/n)? ')): raise for colorcmd, table in zip([Command.PMGammaRed, Command.PMGammaGreen, Command.PMGammaBlue], newgamma): write_gamma_curve(jvc=jvc, colorcmd=colorcmd, table=table, verify=verify) self.file_save(basename='written-{}'.format(old_gamma_table.name), save_all_params=False)
def __init__(self): """JVC gamma table select, plot, load menu""" self.autoplot = 2 self.autoplot_history = 1 self.gamma = GammaCurve() self.verify = True self.plot = None self.run_plot_open = False self.plot_menu = False self.replot = False self.adjust_menu_on = False self.gammaref = [] try: self.gamma.file_load() except FileNotFoundError: pass except Exception: if not strtobool(input('Failed to load gamma curve.\n' 'Ignore error and continue (y/n)? ')): raise while self.run_plot_open is not None: plot_open = self.run_plot_open self.run_plot_open = None if plot_open: self.run_with_plot() else: self.run()
def _parse_boolean(self, java_boolean): return bool(strtobool(java_boolean.toString()))
def __init__(self, feat_stride='(64, 32, 16, 8, 4)', scales='(8)', ratios='(0.5, 1, 2)', output_score='False', rpn_pre_nms_top_n='12000', rpn_post_nms_top_n='2000', threshold='0.3', rpn_min_size='16', output_pyramid_rois='False'): super(PyramidProposalProp, self).__init__(need_top_grad=False) self._feat_stride = 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) self.output_pyramid_rois = strtobool(output_pyramid_rois)
def force_kill (self, confirm = True): """ Force killing of running TRex process (if exists) on the server. .. tip:: This method is a safety method and **overrides any running or reserved resources**, and as such isn't designed to be used on a regular basis. Always consider using :func:`trex_client.CTRexClient.stop_trex` instead. In the end of this method, TRex will return to IDLE state with no reservation. :parameters: confirm : bool Prompt a user confirmation before continue terminating TRex session :return: + **True** on successful termination + **False** otherwise. :raises: + ProtocolError, in case of error in JSON-RPC protocol. """ if confirm: prompt = "WARNING: This will terminate active TRex session indiscriminately.\nAre you sure? " sys.stdout.write('%s [y/n]\n' % prompt) while True: try: if strtobool(user_input().lower()): break else: return except ValueError: sys.stdout.write('Please respond with \'y\' or \'n\'.\n') try: return self.server.force_trex_kill() except AppError as err: # Silence any kind of application errors- by design return False except ProtocolError: raise finally: self.prompt_verbose_data()
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 # handle multiline configs if option.action == 'append': val = val.split() else: option.nargs = 1 if option.action in ('store_true', 'store_false', 'count'): val = strtobool(val) try: val = option.convert_value(key, val) except optparse.OptionValueError: e = sys.exc_info()[1] print("An error occurred during configuration: %s" % e) sys.exit(3) defaults[option.dest] = val return defaults