How to use optionxform method in toolium

Best Python code snippet using toolium_python

ConfigParser.py

Source:ConfigParser.py Github

copy

Full Screen

...162 self._sections = self._dict()163 self._defaults = self._dict()164 if defaults:165 for key, value in defaults.items():166 self._defaults[self.optionxform(key)] = value167 def defaults(self):168 return self._defaults169 def sections(self):170 """Return a list of section names, excluding [DEFAULT]"""171 # self._sections will never have [DEFAULT] in it172 return self._sections.keys()173 def add_section(self, section):174 """Create a new section in the configuration.175 Raise DuplicateSectionError if a section by the specified name176 already exists. Raise ValueError if name is DEFAULT or any of it's177 case-insensitive variants.178 """179 if section.lower() == "default":180 raise ValueError, 'Invalid section name: %s' % section181 if section in self._sections:182 raise DuplicateSectionError(section)183 self._sections[section] = self._dict()184 def has_section(self, section):185 """Indicate whether the named section is present in the configuration.186 The DEFAULT section is not acknowledged.187 """188 return section in self._sections189 def options(self, section):190 """Return a list of option names for the given section name."""191 try:192 opts = self._sections[section].copy()193 except KeyError:194 raise NoSectionError(section)195 opts.update(self._defaults)196 if '__name__' in opts:197 del opts['__name__']198 return opts.keys()199 def read(self, filenames):200 """Read and parse a filename or a list of filenames.201 Files that cannot be opened are silently ignored; this is202 designed so that you can specify a list of potential203 configuration file locations (e.g. current directory, user's204 home directory, systemwide directory), and all existing205 configuration files in the list will be read. A single206 filename may also be given.207 Return list of successfully read files.208 """209 if isinstance(filenames, basestring):210 filenames = [filenames]211 read_ok = []212 for filename in filenames:213 try:214 fp = open(filename)215 except IOError:216 continue217 self._read(fp, filename)218 fp.close()219 read_ok.append(filename)220 return read_ok221 def readfp(self, fp, filename=None):222 """Like read() but the argument must be a file-like object.223 The `fp' argument must have a `readline' method. Optional224 second argument is the `filename', which if not given, is225 taken from fp.name. If fp has no `name' attribute, `<???>' is226 used.227 """228 if filename is None:229 try:230 filename = fp.name231 except AttributeError:232 filename = '<???>'233 self._read(fp, filename)234 def get(self, section, option):235 opt = self.optionxform(option)236 if section not in self._sections:237 if section != DEFAULTSECT:238 raise NoSectionError(section)239 if opt in self._defaults:240 return self._defaults[opt]241 else:242 raise NoOptionError(option, section)243 elif opt in self._sections[section]:244 return self._sections[section][opt]245 elif opt in self._defaults:246 return self._defaults[opt]247 else:248 raise NoOptionError(option, section)249 def items(self, section):250 try:251 d2 = self._sections[section]252 except KeyError:253 if section != DEFAULTSECT:254 raise NoSectionError(section)255 d2 = self._dict()256 d = self._defaults.copy()257 d.update(d2)258 if "__name__" in d:259 del d["__name__"]260 return d.items()261 def _get(self, section, conv, option):262 return conv(self.get(section, option))263 def getint(self, section, option):264 return self._get(section, int, option)265 def getfloat(self, section, option):266 return self._get(section, float, option)267 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,268 '0': False, 'no': False, 'false': False, 'off': False}269 def getboolean(self, section, option):270 v = self.get(section, option)271 if v.lower() not in self._boolean_states:272 raise ValueError, 'Not a boolean: %s' % v273 return self._boolean_states[v.lower()]274 def optionxform(self, optionstr):275 return optionstr.lower()276 def has_option(self, section, option):277 """Check for the existence of a given option in a given section."""278 if not section or section == DEFAULTSECT:279 option = self.optionxform(option)280 return option in self._defaults281 elif section not in self._sections:282 return False283 else:284 option = self.optionxform(option)285 return (option in self._sections[section]286 or option in self._defaults)287 def set(self, section, option, value):288 """Set an option."""289 if not section or section == DEFAULTSECT:290 sectdict = self._defaults291 else:292 try:293 sectdict = self._sections[section]294 except KeyError:295 raise NoSectionError(section)296 sectdict[self.optionxform(option)] = value297 def write(self, fp):298 """Write an .ini-format representation of the configuration state."""299 if self._defaults:300 fp.write("[%s]\n" % DEFAULTSECT)301 for (key, value) in self._defaults.items():302 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))303 fp.write("\n")304 for section in self._sections:305 fp.write("[%s]\n" % section)306 for (key, value) in self._sections[section].items():307 if key != "__name__":308 fp.write("%s = %s\n" %309 (key, str(value).replace('\n', '\n\t')))310 fp.write("\n")311 def remove_option(self, section, option):312 """Remove an option."""313 if not section or section == DEFAULTSECT:314 sectdict = self._defaults315 else:316 try:317 sectdict = self._sections[section]318 except KeyError:319 raise NoSectionError(section)320 option = self.optionxform(option)321 existed = option in sectdict322 if existed:323 del sectdict[option]324 return existed325 def remove_section(self, section):326 """Remove a file section."""327 existed = section in self._sections328 if existed:329 del self._sections[section]330 return existed331 #332 # Regular expressions for parsing section headers and options.333 #334 SECTCRE = re.compile(335 r'\[' # [336 r'(?P<header>[^]]+)' # very permissive!337 r'\]' # ]338 )339 OPTCRE = re.compile(340 r'(?P<option>[^:=\s][^:=]*)' # very permissive!341 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,342 # followed by separator343 # (either : or =), followed344 # by any # space/tab345 r'(?P<value>.*)$' # everything up to eol346 )347 def _read(self, fp, fpname):348 """Parse a sectioned setup file.349 The sections in setup file contains a title line at the top,350 indicated by a name in square brackets (`[]'), plus key/value351 options lines, indicated by `name: value' format lines.352 Continuations are represented by an embedded newline then353 leading whitespace. Blank lines, lines beginning with a '#',354 and just about everything else are ignored.355 """356 cursect = None # None, or a dictionary357 optname = None358 lineno = 0359 e = None # None, or an exception360 while True:361 line = fp.readline()362 if not line:363 break364 lineno = lineno + 1365 # comment or blank line?366 if line.strip() == '' or line[0] in '#;':367 continue368 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":369 # no leading whitespace370 continue371 # continuation line?372 if line[0].isspace() and cursect is not None and optname:373 value = line.strip()374 if value:375 cursect[optname] = "%s\n%s" % (cursect[optname], value)376 # a section header or option header?377 else:378 # is it a section header?379 mo = self.SECTCRE.match(line)380 if mo:381 sectname = mo.group('header')382 if sectname in self._sections:383 cursect = self._sections[sectname]384 elif sectname == DEFAULTSECT:385 cursect = self._defaults386 else:387 cursect = self._dict()388 cursect['__name__'] = sectname389 self._sections[sectname] = cursect390 # So sections can't start with a continuation line391 optname = None392 # no section header in the file?393 elif cursect is None:394 raise MissingSectionHeaderError(fpname, lineno, line)395 # an option line?396 else:397 mo = self.OPTCRE.match(line)398 if mo:399 optname, vi, optval = mo.group('option', 'vi', 'value')400 if vi in ('=', ':') and ';' in optval:401 # ';' is a comment delimiter only if it follows402 # a spacing character403 pos = optval.find(';')404 if pos != -1 and optval[pos-1].isspace():405 optval = optval[:pos]406 optval = optval.strip()407 # allow empty values408 if optval == '""':409 optval = ''410 optname = self.optionxform(optname.rstrip())411 cursect[optname] = optval412 else:413 # a non-fatal parsing error occurred. set up the414 # exception but keep going. the exception will be415 # raised at the end of the file and will contain a416 # list of all bogus lines417 if not e:418 e = ParsingError(fpname)419 e.append(lineno, repr(line))420 # if any parsing errors occurred, raise an exception421 if e:422 raise e423class ConfigParser(RawConfigParser):424 def get(self, section, option, raw=False, vars=None):425 """Get an option value for a given section.426 All % interpolations are expanded in the return values, based on the427 defaults passed into the constructor, unless the optional argument428 `raw' is true. Additional substitutions may be provided using the429 `vars' argument, which must be a dictionary whose contents overrides430 any pre-existing defaults.431 The section DEFAULT is special.432 """433 d = self._defaults.copy()434 try:435 d.update(self._sections[section])436 except KeyError:437 if section != DEFAULTSECT:438 raise NoSectionError(section)439 # Update with the entry specific variables440 if vars:441 for key, value in vars.items():442 d[self.optionxform(key)] = value443 option = self.optionxform(option)444 try:445 value = d[option]446 except KeyError:447 raise NoOptionError(option, section)448 if raw:449 return value450 else:451 return self._interpolate(section, option, value, d)452 def items(self, section, raw=False, vars=None):453 """Return a list of tuples with (name, value) for each option454 in the section.455 All % interpolations are expanded in the return values, based on the456 defaults passed into the constructor, unless the optional argument457 `raw' is true. Additional substitutions may be provided using the458 `vars' argument, which must be a dictionary whose contents overrides459 any pre-existing defaults.460 The section DEFAULT is special.461 """462 d = self._defaults.copy()463 try:464 d.update(self._sections[section])465 except KeyError:466 if section != DEFAULTSECT:467 raise NoSectionError(section)468 # Update with the entry specific variables469 if vars:470 for key, value in vars.items():471 d[self.optionxform(key)] = value472 options = d.keys()473 if "__name__" in options:474 options.remove("__name__")475 if raw:476 return [(option, d[option])477 for option in options]478 else:479 return [(option, self._interpolate(section, option, d[option], d))480 for option in options]481 def _interpolate(self, section, option, rawval, vars):482 # do the string interpolation483 value = rawval484 depth = MAX_INTERPOLATION_DEPTH485 while depth: # Loop through this until it's done486 depth -= 1487 if "%(" in value:488 value = self._KEYCRE.sub(self._interpolation_replace, value)489 try:490 value = value % vars491 except KeyError, e:492 raise InterpolationMissingOptionError(493 option, section, rawval, e.args[0])494 else:495 break496 if "%(" in value:497 raise InterpolationDepthError(option, section, rawval)498 return value499 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")500 def _interpolation_replace(self, match):501 s = match.group(1)502 if s is None:503 return match.group()504 else:505 return "%%(%s)s" % self.optionxform(s)506class SafeConfigParser(ConfigParser):507 def _interpolate(self, section, option, rawval, vars):508 # do the string interpolation509 L = []510 self._interpolate_some(option, L, rawval, section, vars, 1)511 return ''.join(L)512 _interpvar_re = re.compile(r"%\(([^)]+)\)s")513 def _interpolate_some(self, option, accum, rest, section, map, depth):514 if depth > MAX_INTERPOLATION_DEPTH:515 raise InterpolationDepthError(option, section, rest)516 while rest:517 p = rest.find("%")518 if p < 0:519 accum.append(rest)520 return521 if p > 0:522 accum.append(rest[:p])523 rest = rest[p:]524 # p is no longer used525 c = rest[1:2]526 if c == "%":527 accum.append("%")528 rest = rest[2:]529 elif c == "(":530 m = self._interpvar_re.match(rest)531 if m is None:532 raise InterpolationSyntaxError(option, section,533 "bad interpolation variable reference %r" % rest)534 var = self.optionxform(m.group(1))535 rest = rest[m.end():]536 try:537 v = map[var]538 except KeyError:539 raise InterpolationMissingOptionError(540 option, section, rest, var)541 if "%" in v:542 self._interpolate_some(option, accum, v,543 section, map, depth + 1)544 else:545 accum.append(v)546 else:547 raise InterpolationSyntaxError(548 option, section,...

Full Screen

Full Screen

ini.py

Source:ini.py Github

copy

Full Screen

...259 # identical to __getitem__ except that _compat_XXX260 # is checked for backward-compatible handling261 if key == '__name__':262 return self._lines[-1].name263 if self._optionxform: key = self._optionxform(key)264 try:265 value = self._options[key].value266 del_empty = key in self._compat_skip_empty_lines267 except KeyError:268 if self._defaults and key in self._defaults._options:269 value = self._defaults._options[key].value270 del_empty = key in self._defaults._compat_skip_empty_lines271 else:272 raise273 if del_empty:274 value = re.sub('\n+', '\n', value)275 return value276 def __getitem__(self, key):277 if key == '__name__':278 return self._lines[-1].name279 if self._optionxform: key = self._optionxform(key)280 try:281 return self._options[key].value282 except KeyError:283 if self._defaults and key in self._defaults._options:284 return self._defaults._options[key].value285 else:286 raise287 def __setitem__(self, key, value):288 if self._optionxform: xkey = self._optionxform(key)289 else: xkey = key290 if xkey in self._compat_skip_empty_lines:291 self._compat_skip_empty_lines.remove(xkey)292 if xkey not in self._options:293 # create a dummy object - value may have multiple lines294 obj = LineContainer(OptionLine(key, ''))295 self._lines[-1].add(obj)296 self._options[xkey] = obj297 # the set_value() function in LineContainer298 # automatically handles multi-line values299 self._options[xkey].value = value300 def __delitem__(self, key):301 if self._optionxform: key = self._optionxform(key)302 if key in self._compat_skip_empty_lines:303 self._compat_skip_empty_lines.remove(key)304 for l in self._lines:305 remaining = []306 for o in l.contents:307 if isinstance(o, LineContainer):308 n = o.name309 if self._optionxform: n = self._optionxform(n)310 if key != n: remaining.append(o)311 else:312 remaining.append(o)313 l.contents = remaining314 del self._options[key]315 def __iter__(self):316 d = set()317 for l in self._lines:318 for x in l.contents:319 if isinstance(x, LineContainer):320 if self._optionxform:321 ans = self._optionxform(x.name)322 else:323 ans = x.name324 if ans not in d:325 yield ans326 d.add(ans)327 if self._defaults:328 for x in self._defaults:329 if x not in d:330 yield x331 d.add(x)332 def _new_namespace(self, name):333 raise Exception('No sub-sections allowed', name)334def make_comment(line):335 return CommentLine(line.rstrip('\n'))336def readline_iterator(f):337 """iterate over a file by only using the file object's readline method"""338 have_newline = False339 while True:340 line = f.readline()341 if not line:342 if have_newline:343 yield ""344 return345 if line.endswith('\n'):346 have_newline = True347 else:348 have_newline = False349 yield line350def lower(x):351 return x.lower()352class INIConfig(config.ConfigNamespace):353 _data = None354 _sections = None355 _defaults = None356 _optionxformvalue = None357 _optionxformsource = None358 _sectionxformvalue = None359 _sectionxformsource = None360 _parse_exc = None361 _bom = False362 def __init__(self, fp=None, defaults=None, parse_exc=True,363 optionxformvalue=lower, optionxformsource=None,364 sectionxformvalue=None, sectionxformsource=None):365 self._data = LineContainer()366 self._parse_exc = parse_exc367 self._optionxformvalue = optionxformvalue368 self._optionxformsource = optionxformsource369 self._sectionxformvalue = sectionxformvalue370 self._sectionxformsource = sectionxformsource371 self._sections = {}372 if defaults is None: defaults = {}373 self._defaults = INISection(LineContainer(), optionxformsource=self)374 for name, value in defaults.iteritems():375 self._defaults[name] = value376 if fp is not None:377 self._readfp(fp)378 _optionxform = _make_xform_property('_optionxform', 'optionxform')379 _sectionxform = _make_xform_property('_sectionxform', 'optionxform')380 def __getitem__(self, key):381 if key == DEFAULTSECT:382 return self._defaults383 if self._sectionxform: key = self._sectionxform(key)384 return self._sections[key]385 def __setitem__(self, key, value):386 raise Exception('Values must be inside sections', key, value)387 def __delitem__(self, key):388 if self._sectionxform: key = self._sectionxform(key)389 for line in self._sections[key]._lines:390 self._data.contents.remove(line)391 del self._sections[key]392 def __iter__(self):393 d = set()394 d.add(DEFAULTSECT)395 for x in self._data.contents:396 if isinstance(x, LineContainer):397 if x.name not in d:398 yield x.name399 d.add(x.name)400 def _new_namespace(self, name):401 if self._data.contents:402 self._data.add(EmptyLine())403 obj = LineContainer(SectionLine(name))404 self._data.add(obj)405 if self._sectionxform: name = self._sectionxform(name)406 if name in self._sections:407 ns = self._sections[name]408 ns._lines.append(obj)409 else:410 ns = INISection(obj, defaults=self._defaults,411 optionxformsource=self)412 self._sections[name] = ns413 return ns414 def __str__(self):415 if self._bom:416 fmt = u'\ufeff%s'417 else:418 fmt = '%s'419 return fmt % self._data.__str__()420 __unicode__ = __str__421 _line_types = [EmptyLine, CommentLine,422 SectionLine, OptionLine,423 ContinuationLine]424 def _parse(self, line):425 for linetype in self._line_types:426 lineobj = linetype.parse(line)427 if lineobj:428 return lineobj429 else:430 # can't parse line431 return None432 def _readfp(self, fp):433 cur_section = None434 cur_option = None435 cur_section_name = None436 cur_option_name = None437 pending_lines = []438 pending_empty_lines = False439 try:440 fname = fp.name441 except AttributeError:442 fname = '<???>'443 linecount = 0444 exc = None445 line = None446 for line in readline_iterator(fp):447 # Check for BOM on first line448 if linecount == 0 and isinstance(line, unicode):449 if line[0] == u'\ufeff':450 line = line[1:]451 self._bom = True452 lineobj = self._parse(line)453 linecount += 1454 if not cur_section and not isinstance(lineobj,455 (CommentLine, EmptyLine, SectionLine)):456 if self._parse_exc:457 raise MissingSectionHeaderError(fname, linecount, line)458 else:459 lineobj = make_comment(line)460 if lineobj is None:461 if self._parse_exc:462 if exc is None: exc = ParsingError(fname)463 exc.append(linecount, line)464 lineobj = make_comment(line)465 if isinstance(lineobj, ContinuationLine):466 if cur_option:467 if pending_lines:468 cur_option.extend(pending_lines)469 pending_lines = []470 if pending_empty_lines:471 optobj._compat_skip_empty_lines.add(cur_option_name)472 pending_empty_lines = False473 cur_option.add(lineobj)474 else:475 # illegal continuation line - convert to comment476 if self._parse_exc:477 if exc is None: exc = ParsingError(fname)478 exc.append(linecount, line)479 lineobj = make_comment(line)480 if isinstance(lineobj, OptionLine):481 if pending_lines:482 cur_section.extend(pending_lines)483 pending_lines = []484 pending_empty_lines = False485 cur_option = LineContainer(lineobj)486 cur_section.add(cur_option)487 if self._optionxform:488 cur_option_name = self._optionxform(cur_option.name)489 else:490 cur_option_name = cur_option.name491 if cur_section_name == DEFAULTSECT:492 optobj = self._defaults493 else:494 optobj = self._sections[cur_section_name]495 optobj._options[cur_option_name] = cur_option496 if isinstance(lineobj, SectionLine):497 self._data.extend(pending_lines)498 pending_lines = []499 pending_empty_lines = False500 cur_section = LineContainer(lineobj)501 self._data.add(cur_section)502 cur_option = None...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run toolium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful