本文整理汇总了Python中string.Formatter.vformat方法的典型用法代码示例。如果您正苦于以下问题:Python Formatter.vformat方法的具体用法?Python Formatter.vformat怎么用?Python Formatter.vformat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Formatter
的用法示例。
在下文中一共展示了Formatter.vformat方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vformat
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def vformat(self, format_string, args, kwargs):
self.unused_args = {}
ret = Formatter.vformat(self, format_string, args, kwargs)
if not self.unused_args:
return ret
extra_data = ', '.join('{0}={1}'.format(*kv) for kv in self.unused_args.items())
return '{0} ({1})'.format(ret, extra_data)
示例2: vformat
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def vformat(self, format_string, args, kwargs):
matcher = re.compile(self._expr, re.VERBOSE)
# special case of returning the object if the entire string
# matches a single parameter
try:
result = re.match('^%s$' % self._expr, format_string, re.VERBOSE)
except TypeError:
return format_string.format(**kwargs)
if result is not None:
try:
return kwargs[result.group("key")]
except KeyError:
pass
# handle multiple fields within string via a callback to re.sub()
def re_replace(match):
key = match.group("key")
default = match.group("default")
if default is not None:
if key not in kwargs:
return default
else:
return "{%s}" % key
return match.group(0)
format_string = matcher.sub(re_replace, format_string)
return Formatter.vformat(self, format_string, args, kwargs)
示例3: pformat
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def pformat(temp, **fmt):
"""Format a template string partially.
Examples
--------
>>> pformat("{a}_{b}", a='x')
'x_{b}'
"""
formatter = Formatter()
mapping = _FormatDict(fmt)
return formatter.vformat(temp, (), mapping)
示例4: make_tag
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def make_tag():
today = datetime.datetime.today()
date = today.strftime(date_format)
print(date)
seq=1
"git tag --list=release/%s/*" % date
values={
"date": date,
"sequence": seq
}
formatter = Formatter()
tag = formatter.vformat(tag_format, [], values)
print(tag)
示例5: _write_to_file
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def _write_to_file(table_a_dest,
genome_ids_a,
genome_ids_b,
common_prefix_a,
common_prefix_b,
calculations):
'''
:param table_a_dest:
:type table_a_dest: filename
:param genome_ids_a:
:type genome_ids_a: list or genome ids
:param common_prefix_a:
:type common_prefix_a: string
:param common_prefix_b:
:type common_prefix_b: string
:param calculations:
:type calculations: list of clade_calcs instances
'''
with open(table_a_dest, 'a') as write_handle:
# Print introduction about the strain comparison
write_handle.write('#{} {} strains compared with {} {} strains\n'.format(len(genome_ids_a),
common_prefix_a,
len(genome_ids_b),
common_prefix_b))
# Print the genome IDs involved in each of the strains
write_handle.write('#IDs {}: {}\n'.format(common_prefix_a,
', '.join(genome_ids_a)))
write_handle.write('#IDs {}: {}\n'.format(common_prefix_b,
', '.join(genome_ids_b)))
# Print column headers for the data to come
max_nton = len(genome_ids_a) // 2
headers = _get_column_headers(max_nton)
write_handle.write('#' + '\t'.join(headers))
write_handle.write('\n')
# Print data rows
format_str = '\t'.join('{{{}}}'.format(key) for key in headers)
from string import Formatter
formatter = Formatter()
for clade_calcs in calculations:
write_handle.write(formatter.vformat(format_str, None, clade_calcs.values))
write_handle.write('\n')
示例6: resolve_conf
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def resolve_conf(unresolved):
"""take a config with values using string formatting; apply string formatting until they all don't;
returns (dict of things that could be resolved, dict of things that couldn't be resolved)"""
f = Formatter()
resolved = {}
while unresolved:
changed_something, missing_defs = False, []
for k, v in unresolved.items():
if isinstance(v, basestring) and v and tuple(f.parse(v))[0][1] is not None:
try:
unresolved[k] = f.vformat(v, [], resolved)
changed_something = True
except KeyError, e: # missing a definition; but could in the next pass if we changed something
missing_defs.append(e.args[0])
else:
# non strings are, by definition, resolved; no recursion into complex data structures here
# items without format specifiers are also resolved
del unresolved[k]
resolved[k] = v
changed_something = True
if not changed_something:
break
示例7: on_query_completions
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def on_query_completions(self, view, prefix, locations):
# Only trigger within LaTeX
if not view.match_selector(locations[0],
"text.tex.latex"):
return []
point = locations[0]
try:
completions, prefix, post_brace, new_point_a, new_point_b = get_cite_completions(view, point, autocompleting=True)
except UnrecognizedCiteFormatError:
return []
except NoBibFilesError:
sublime.status_message("No bib files found!")
return []
except BibParsingError as e:
sublime.status_message("Bibliography " + e.filename + " is broken!")
return []
# filter against keyword or title
if prefix:
completions = [comp for comp in completions if prefix.lower() in "%s %s" %
(
comp['keyword'].lower(),
comp['title'].lower())]
prefix += " "
# get preferences for formating of autocomplete entries
cite_autocomplete_format = get_setting('cite_autocomplete_format',
"{keyword}: {title}")
formatter = Formatter()
r = [(prefix + formatter.vformat(cite_autocomplete_format, (), completion),
completion['keyword'] + post_brace) for completion in completions]
# print "%d bib entries matching %s" % (len(r), prefix)
return r
示例8: run
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def run(self, edit):
# get view and location of first selection, which we expect to be just the cursor position
view = self.view
point = view.sel()[0].b
print (point)
# Only trigger within LaTeX
# Note using score_selector rather than match_selector
if not view.score_selector(point,
"text.tex.latex"):
return
try:
completions, prefix, post_brace, new_point_a, new_point_b = get_cite_completions(view, point)
except UnrecognizedCiteFormatError:
sublime.error_message("Not a recognized format for citation completion")
return
except NoBibFilesError:
sublime.error_message("No bib files found!")
return
except BibParsingError as e:
sublime.error_message("Bibliography " + e.filename + " is broken!")
return
except BibParsingError as e:
sublime.error_message(e.message)
return
# filter against keyword, title, or author
if prefix:
completions = [comp for comp in completions if prefix.lower() in "%s %s %s" %
(
comp['keyword'].lower(),
comp['title'].lower(),
comp['author'].lower())]
# Note we now generate citation on the fly. Less copying of vectors! Win!
def on_done(i):
print ("latex_cite_completion called with index %d" % (i,) )
# Allow user to cancel
if i < 0:
return
keyword = completions[i]['keyword']
# notify any plugins
notification_thread = threading.Thread(
target=run_plugin_command,
args=(
'on_insert_citation',
keyword
),
kwargs={
'stop_on_first': False,
'expect_result': False
}
)
notification_thread.daemon = True
notification_thread.start()
cite = completions[i]['keyword'] + post_brace
#print("DEBUG: types of new_point_a and new_point_b are " + repr(type(new_point_a)) + " and " + repr(type(new_point_b)))
# print "selected %s:%s by %s" % completions[i][0:3]
# Replace cite expression with citation
# the "latex_tools_replace" command is defined in latex_ref_cite_completions.py
view.run_command("latex_tools_replace", {"a": new_point_a, "b": new_point_b, "replacement": cite})
# Unselect the replaced region and leave the caret at the end
caret = view.sel()[0].b
view.sel().subtract(view.sel()[0])
view.sel().add(sublime.Region(caret, caret))
# get preferences for formating of quick panel
cite_panel_format = get_setting('cite_panel_format',
["{title} ({keyword})", "{author}"])
completions_length = len(completions)
if completions_length == 0:
return
elif completions_length == 1:
# only one entry, so insert entry
view.run_command("latex_tools_replace",
{
"a": new_point_a,
"b": new_point_b,
"replacement": completions[0]['keyword'] + post_brace
}
)
# Unselect the replaced region and leave the caret at the end
caret = view.sel()[0].b
view.sel().subtract(view.sel()[0])
view.sel().add(sublime.Region(caret, caret))
else:
# show quick
formatter = Formatter()
view.window().show_quick_panel([[formatter.vformat(s, (), completion) for s in cite_panel_format] \
for completion in completions], on_done)
示例9: Env
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
class Env(object):
"""
Stores config settings for fusionbox fabric helper routines. Dynamically
builds the value of certain properties unless their value was manually set.
NOTE:
Be careful not to define properties that reference each other...will cause
a stack overflow.
"""
DEFAULTS = {
# Global defaults
"transport_method": "git",
"tld": ".com",
"web_home": "/var/www",
"workon_home": "/var/python-environments",
"backups_dir": "backups",
"media_dir": "media",
"virtualenv": "{project_name}",
"vassal": "{project_name}",
# Dev defaults
"dev_project_name": "{project_name}",
"dev_tld": "{tld}",
"dev_web_home": "{web_home}",
"dev_virtualenv": "{virtualenv}",
"dev_vassal": "{vassal}",
"dev_workon_home": "{workon_home}",
"dev_project_dir": "{dev_project_name}{dev_tld}",
"dev_project_path": "{dev_web_home}/{dev_project_dir}",
"dev_virtualenv_path": "{dev_workon_home}/{dev_virtualenv}",
"dev_restart_cmd": "sudo touch /etc/vassals/{dev_vassal}.ini",
"dev_backups_dir": "{backups_dir}",
"dev_media_dir": "{media_dir}",
"dev_media_path": "{dev_project_path}/{dev_media_dir}",
# Live defaults
"live_project_name": "{project_name}",
"live_tld": "{tld}",
"live_web_home": "{web_home}",
"live_virtualenv": "{virtualenv}",
"live_vassal": "{vassal}",
"live_workon_home": "{workon_home}",
"live_project_dir": "{live_project_name}{live_tld}",
"live_project_path": "{live_web_home}/{live_project_dir}",
"live_virtualenv_path": "{live_workon_home}/{live_virtualenv}",
"live_restart_cmd": "sudo touch /etc/vassals/{live_vassal}.ini",
"live_backups_dir": "{backups_dir}",
"live_media_dir": "{media_dir}",
"live_media_path": "{live_project_path}/{live_media_dir}",
# Local defaults
"local_backups_dir": "{backups_dir}",
"local_media_dir": "{media_dir}",
}
def __init__(self):
self._formatter = Formatter()
def __getattr__(self, name):
if name in self.DEFAULTS:
# If there is a default value format, build the default value
return self._format(self.DEFAULTS[name])
else:
raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, name))
def __getitem__(self, key):
return getattr(self, key)
def _format(self, f):
# Use a string formatter instance so we can use any object that defines
# __getitem__
return self._formatter.vformat(f, None, self)
def role(self, role, name):
return getattr(self, role + "_" + name)
示例10: dictformat
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def dictformat(string, dictionary):
formatter = Formatter()
return formatter.vformat(string, (), dictionary)
示例11: test_dot
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import vformat [as 别名]
def test_dot(self):
f=Formatter()
x=Str('bla')
x.x='foo'
self.assertEqual(f.vformat('{x}{x.x}',[], {'x':x}), 'blafoo')