本文整理匯總了Python中builtins.format方法的典型用法代碼示例。如果您正苦於以下問題:Python builtins.format方法的具體用法?Python builtins.format怎麽用?Python builtins.format使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類builtins
的用法示例。
在下文中一共展示了builtins.format方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handle_enddef
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def handle_enddef(self, span, name):
'''Should be called to signalize an enddef directive.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the enddef statement. Could be None, if enddef
was specified without name.
'''
self._check_for_open_block(span, 'enddef')
block = self._open_blocks.pop(-1)
directive, fname, spans = block[0:3]
self._check_if_matches_last(directive, 'def', spans[-1], span, 'enddef')
defname, argexpr, dummy = block[3:6]
if name is not None and name != defname:
msg = "wrong name in enddef directive "\
"(expected '{0}', got '{1}')".format(defname, name)
raise FyppFatalError(msg, fname, span)
spans.append(span)
block = (directive, fname, spans, defname, argexpr, self._curnode)
self._curnode = self._path.pop(-1)
self._curnode.append(block)
示例2: _check_if_matches_last
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _check_if_matches_last(self, lastdir, curdir, lastspan, curspan,
directive):
if curdir != lastdir:
msg = "mismatching '{0}' directive (last block opened was '{1}')"\
.format(directive, lastdir)
raise FyppFatalError(msg, self._curfile, curspan)
inline_last = lastspan[0] == lastspan[1]
inline_cur = curspan[0] == curspan[1]
if inline_last != inline_cur:
if inline_cur:
msg = 'expecting line form of directive {0}'.format(directive)
else:
msg = 'expecting inline form of directive {0}'.format(directive)
raise FyppFatalError(msg, self._curfile, curspan)
elif inline_cur and curspan[0] != lastspan[0]:
msg = 'inline directives of the same construct must be in the '\
'same row'
raise FyppFatalError(msg, self._curfile, curspan)
示例3: _get_eval
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _get_eval(self, fname, span, expr):
try:
result = self._evaluate(expr, fname, span[0])
except Exception as exc:
msg = "exception occurred when evaluating '{0}'".format(expr)
raise FyppFatalError(msg, fname, span, exc)
out = []
ieval = []
peval = []
if result is not None:
out.append(str(result))
if not self._diverted:
ieval.append(0)
peval.append((span, fname))
if span[0] != span[1]:
out.append('\n')
return out, ieval, peval
示例4: _get_conditional_content
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _get_conditional_content(self, fname, spans, conditions, contents):
out = []
ieval = []
peval = []
multiline = (spans[0][0] != spans[-1][1])
for condition, content, span in zip(conditions, contents, spans):
try:
cond = bool(self._evaluate(condition, fname, span[0]))
except Exception as exc:
msg = "exception occurred when evaluating '{0}'"\
.format(condition)
raise FyppFatalError(msg, fname, span, exc)
if cond:
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(span[1], fname))
outcont, ievalcont, pevalcont = self._render(content)
ieval += _shiftinds(ievalcont, len(out))
peval += pevalcont
out += outcont
break
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(spans[-1][1], fname))
return out, ieval, peval
示例5: _define_variable
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _define_variable(self, fname, span, name, valstr):
result = ''
try:
if valstr is None:
expr = None
else:
expr = self._evaluate(valstr, fname, span[0])
self._define(name, expr)
except Exception as exc:
msg = "exception occurred when setting variable(s) '{0}' to '{1}'"\
.format(name, valstr)
raise FyppFatalError(msg, fname, span, exc)
multiline = (span[0] != span[1])
if self._linenums and not self._diverted and multiline:
result = linenumdir(span[1], fname)
return result
示例6: import_module
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def import_module(self, module):
'''Import a module into the evaluator.
Note: Import only trustworthy modules! Module imports are global,
therefore, importing a malicious module which manipulates other global
modules could affect code behaviour outside of the Evaluator as well.
Args:
module (str): Python module to import.
Raises:
FyppFatalError: If module could not be imported.
'''
rootmod = module.split('.', 1)[0]
try:
imported = __import__(module, self._scope)
self.define(rootmod, imported)
except Exception as exc:
msg = "failed to import module '{0}'".format(module)
raise FyppFatalError(msg, cause=exc)
示例7: addglobal
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def addglobal(self, name):
'''Define a given entity as global.
Args:
name (str): Name of the entity to make global.
Raises:
FyppFatalError: If entity name is invalid or if the current scope is
a local scope and entity is already defined in it.
'''
varnames = self._get_variable_names(name)
for varname in varnames:
self._check_variable_name(varname)
if self._locals is not None:
if varname in self._locals:
msg = "variable '{0}' already defined in local scope"\
.format(varname)
raise FyppFatalError(msg)
self._globalrefs.add(varname)
示例8: __init__
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def __init__(self, maxlen=132, indent=4, method='smart', prefix='&',
suffix='&'):
# Line length should be long enough that contintuation lines can host at
# east one character apart of indentation and two continuation signs
minmaxlen = indent + len(prefix) + len(suffix) + 1
if maxlen < minmaxlen:
msg = 'Maximal line length less than {0} when using an indentation'\
' of {1}'.format(minmaxlen, indent)
raise FyppFatalError(msg)
self._maxlen = maxlen
self._indent = indent
self._prefix = ' ' * self._indent + prefix
self._suffix = suffix
if method not in ['brute', 'smart', 'simple']:
raise FyppFatalError('invalid folding type')
if method == 'brute':
self._inherit_indent = False
self._fold_position_finder = self._get_maximal_fold_pos
elif method == 'simple':
self._inherit_indent = True
self._fold_position_finder = self._get_maximal_fold_pos
elif method == 'smart':
self._inherit_indent = True
self._fold_position_finder = self._get_smart_fold_pos
示例9: _open_output_file
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _open_output_file(outfile, encoding=None, create_parents=False):
if create_parents:
parentdir = os.path.abspath(os.path.dirname(outfile))
if not os.path.exists(parentdir):
try:
os.makedirs(parentdir)
except OSError as exc:
if exc.errno != errno.EEXIST:
msg = "Folder '{0}' can not be created"\
.format(parentdir)
raise FyppFatalError(msg, cause=exc)
try:
outfp = io.open(outfile, 'w', encoding=encoding)
except IOError as exc:
msg = "Failed to open file '{0}' for write".format(outfile)
raise FyppFatalError(msg, cause=exc)
return outfp
示例10: _get_callable_argspec_py3
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _get_callable_argspec_py3(func):
sig = inspect.signature(func)
args = []
defaults = {}
varpos = None
varkw = None
for param in sig.parameters.values():
if param.kind == param.POSITIONAL_OR_KEYWORD:
args.append(param.name)
if param.default != param.empty:
defaults[param.name] = param.default
elif param.kind == param.VAR_POSITIONAL:
varpos = param.name
elif param.kind == param.VAR_KEYWORD:
varkw = param.name
else:
msg = "argument '{0}' has invalid argument type".format(param.name)
raise FyppFatalError(msg)
return args, defaults, varpos, varkw
# Signature objects are available from Python 3.3 (and deprecated from 3.5)
示例11: _formatted_exception
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _formatted_exception(exc):
error_header_formstr = '{file}:{line}: '
error_body_formstr = 'error: {errormsg} [{errorclass}]'
if not isinstance(exc, FyppError):
return error_body_formstr.format(
errormsg=str(exc), errorclass=exc.__class__.__name__)
out = []
if exc.fname is not None:
if exc.span[1] > exc.span[0] + 1:
line = '{0}-{1}'.format(exc.span[0] + 1, exc.span[1])
else:
line = '{0}'.format(exc.span[0] + 1)
out.append(error_header_formstr.format(file=exc.fname, line=line))
out.append(error_body_formstr.format(errormsg=exc.msg,
errorclass=exc.__class__.__name__))
if exc.cause is not None:
out.append('\n' + _formatted_exception(exc.cause))
out.append('\n')
return ''.join(out)
示例12: format
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def format(self):
"""Format of output file.
Raises:
UnsupportedCall: If :attr:`self._flag_q <pcapkit.foundation.extraction.Extractor._flag_q>`
is set as :data:`True`, as output is disabled by initialisation parameter.
:rtype: str
"""
if self._flag_q:
raise UnsupportedCall("'Extractor(nofile=True)' object has no attribute 'format'")
return self._type
示例13: output
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def output(self):
"""Name of output file.
Raises:
UnsupportedCall: If :attr:`self._flag_q <pcapkit.foundation.extraction.Extractor._flag_q>`
is set as :data:`True`, as output is disabled by initialisation parameter.
:rtype: str
"""
if self._flag_q:
raise UnsupportedCall("'Extractor(nofile=True)' object has no attribute 'format'")
return self._ofnm
示例14: __str__
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def __str__(self):
msg = [self.__class__.__name__, ': ']
if self.fname is not None:
msg.append("file '" + self.fname + "'")
if self.span[1] > self.span[0] + 1:
msg.append(', lines {0}-{1}'.format(
self.span[0] + 1, self.span[1]))
else:
msg.append(', line {0}'.format(self.span[0] + 1))
msg.append('\n')
if self.msg:
msg.append(self.msg)
if self.cause is not None:
msg.append('\n' + str(self.cause))
return ''.join(msg)
示例15: _log_event
# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import format [as 別名]
def _log_event(event, span=(-1, -1), **params):
print('{0}: {1} --> {2}'.format(event, span[0], span[1]))
for parname, parvalue in params.items():
print(' {0}: ->|{1}|<-'.format(parname, parvalue))
print()