def loadAll(self): """Load the user prefs and the application data """ self._validator = validate.Validator() # note: self.paths['userPrefsDir'] gets set in loadSitePrefs() self.paths['appDataFile'] = join(self.paths['userPrefsDir'], 'appData.cfg') self.paths['userPrefsFile'] = join(self.paths['userPrefsDir'], 'userPrefs.cfg') # If PsychoPy is tucked away by Py2exe in library.zip, the preferences # file cannot be found. This hack is an attempt to fix this. libzip = "\\library.zip\\psychopy\\preferences\\" if libzip in self.paths["prefsSpecFile"]: self.paths["prefsSpecFile"] = self.paths["prefsSpecFile"].replace( libzip, "\\resources\\") self.userPrefsCfg = self.loadUserPrefs() self.appDataCfg = self.loadAppData() self.validate() # simplify namespace self.general = self.userPrefsCfg['general'] self.app = self.userPrefsCfg['app'] self.coder = self.userPrefsCfg['coder'] self.builder = self.userPrefsCfg['builder'] self.hardware = self.userPrefsCfg['hardware'] self.connections = self.userPrefsCfg['connections'] self.keys = self.userPrefsCfg['keyBindings'] self.appData = self.appDataCfg # keybindings: self.keys = self.userPrefsCfg['keyBindings']
def getConfig(): global _config if not _config: path = os.path.join(config.getUserDefaultConfigPath(), "ocr.ini") _config = configobj.ConfigObj(path, configspec=configspec) val = validate.Validator() _config.validate(val) return _config
def get_config(): global _config if not _config: path = os.path.abspath( os.path.join(globalVars.appArgs.configPath, CONFIG_FILE_NAME)) _config = configobj.ConfigObj(infile=path, configspec=configspec, create_empty=True) val = validate.Validator() _config.validate(val, copy=True) return _config
def restoreBadPrefs(self, cfg, result): """result = result of validate """ if result == True: return vtor = validate.Validator() for sectionList, key, _ in configobj.flatten_errors(cfg, result): if key is not None: _secList = ', '.join(sectionList) val = cfg.configspec[_secList][key] cfg[_secList][key] = vtor.get_default_value(val) else: msg = "Section [%s] was missing in file '%s'" print(msg % (', '.join(sectionList), cfg.filename))
length = int(length) if not isinstance(value, str): raise validate.VdtTypeError(value) try: data = base64.b64decode(value) except binascii.Error: raise validate.VdtValueError(value) if length is not None and len(data) != length: raise validate.VdtValueError(value) return data validator = validate.Validator({ 'timedelta': is_timedelta, 'optionlist': is_optionlist, 'task_list': is_task_list, 'file': is_file, 'base64bytes': is_base64bytes, }) class AttrAccess: """Provide attribute access to mappings, supporting nesting""" EMPTY_INST = type('', (), {'__repr__': lambda s: 'AttrAccess.EMPTY_INST'})() def __init__(self, mapping): self.mapping = mapping def get(self, item, fallback=EMPTY_INST): """return ``item`` if present, otherwise the given fallback
def get_cfg(cfg_file_name="Parameters.in", kvargs={}, err=sys.stderr): """ Parse a config """ def validate_convert(value, func, name=None): """Helper function for validate parameter conversion""" if value is None: return None try: return func(value) except (TypeError, ValueError): if name is None: raise validate.VdtValueError(value) else: raise validate.VdtParamError(name, value) def sci_int(val): """Converts type to int, honouring scientific notation if possible""" try: i = int(val) except ValueError: val = float(val) i = int(val) if type(val)(i) != val: raise ValueError("Not exactly representable as integer") return i def is_sci_integer(value, min=None, max=None): """Function for the validate module to support scientific notation""" value = validate_convert(value, sci_int) minval = validate_convert(min, sci_int, "min") maxval = validate_convert(max, sci_int, "max") if min is not None and value < minval: raise validate.VdtValueTooSmallError(value) if max is not None and value > maxval: raise validate.VdtValueTooBigError(value) return value def is_option_or_float_list(value, *options): try: return validate.is_option(value, *options) except validate.VdtTypeError: return validate.is_float_list(value) # config configspec = open(os.path.dirname(__file__) + '/configspec', 'r') cfg = configobj.ConfigObj(infile=open(cfg_file_name, 'r'), configspec=configspec.readlines(), indent_type="\t") # update command line parameters for key in kvargs: groups = key.split(".") parent = cfg for group in groups[:-1]: parent = parent[group] parent[groups[-1]] = kvargs[key] validator = validate.Validator() validator.functions["integer"] = is_sci_integer validator.functions["option_or_list"] = is_option_or_float_list valid = cfg.validate(validator, copy=True) try: pairs = configobj.get_extra_values(cfg) except AttributeError: print("WARNING: cannot check unknown entries in config", file=err) pairs = False if pairs: print("error: unknown entries in config: %s" % cfg_file_name, file=err) print(">>>", ", ".join(".".join(e[0] + e[1:]) for e in pairs), file=err) raise CfgException() if valid is not True: print("error: invalid entries in config: %s" % cfg_file_name, file=err) print(">>>", ", ".join( str(entry) for entry, ok in flat_items(valid) if not ok), file=err) raise CfgException() return cfg