本文整理汇总了Python中string.Template方法的典型用法代码示例。如果您正苦于以下问题:Python string.Template方法的具体用法?Python string.Template怎么用?Python string.Template使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string
的用法示例。
在下文中一共展示了string.Template方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_template_strings
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def process_template_strings(data):
"""
Replaces $variables in strings with corresponding variables in plugin data
"""
for plugin_name, plugin_data in data.items():
version = plugin_data['version']
guid = plugin_data['guid']
for key, value in plugin_data.items():
if key == 'version':
continue
if not isinstance(value, str):
continue
# Replace references to $name and $version with the real values
data[plugin_name][key] = Template(value).substitute(
name=plugin_name,
version=version,
guid=guid)
return data
示例2: __init__
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def __init__(self, fmt=None, datefmt=None, style='%'):
"""
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a
default as described above. Allow for specialized date formatting with
the optional datefmt argument (if omitted, you get the ISO8601 format).
Use a style parameter of '%', '{' or '$' to specify that you want to
use one of %-formatting, :meth:`str.format` (``{}``) formatting or
:class:`string.Template` formatting in your format string.
.. versionchanged: 3.2
Added the ``style`` parameter.
"""
if style not in _STYLES:
raise ValueError('Style must be one of: %s' % ','.join(
_STYLES.keys()))
self._style = _STYLES[style](fmt)
self._fmt = self._style._fmt
self.datefmt = datefmt
示例3: get_param_specs
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def get_param_specs(spec):
'''Return a list of specs with substituted spec_params'''
assert 'spec_params' in spec, 'Parametrized spec needs a spec_params key'
spec_params = spec.pop('spec_params')
spec_template = Template(json.dumps(spec))
keys = spec_params.keys()
specs = []
for idx, vals in enumerate(itertools.product(*spec_params.values())):
spec_str = spec_template.substitute(dict(zip(keys, vals)))
spec = json.loads(spec_str)
spec['name'] += f'_{"_".join(vals)}'
# offset to prevent parallel-run GPU competition, to mod in util.set_cuda_id
cuda_id_gap = int(spec['meta']['max_session'] / spec['meta']['param_spec_process'])
spec['meta']['cuda_offset'] += idx * cuda_id_gap
specs.append(spec)
return specs
示例4: mk_module_code
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def mk_module_code(code_info: PyCodeInfo):
freevars = code_info.freevars
argnames = code_info.argnames
method_name = "method"
method_getter_invoker_name = "invoke_method_get"
while method_name in argnames:
method_name += "_emm"
while method_getter_invoker_name in argnames:
method_name += "_emm"
arguments = freevars + argnames
argc = len(arguments)
unnamed_args = ['a%d' % i for i in range(argc)]
return Template(template).substitute(
method=method_name,
many_objects=', '.join(['object'] * argc),
many_int64_t=', '.join(['int64_t'] * argc),
unnamed_args=", ".join(unnamed_args),
typeids=mk_call_record(unnamed_args),
method_get_invoker=method_getter_invoker_name,
arguments=', '.join(arguments))
示例5: load_secrets_file
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def load_secrets_file(config_dict: dict) -> dict:
from string import Template
import ast
gn_env = os.getenv(ENV_KEY_ENVIRONMENT)
secrets_path = os.getenv(ENV_KEY_SECRETS)
if secrets_path is None:
secrets_path = 'secrets/%s.yaml' % gn_env
logger.debug('loading secrets file "%s"' % secrets_path)
# first substitute environment variables, which holds precedence over the yaml config (if it exists)
template = Template(str(config_dict))
template = template.safe_substitute(os.environ)
if os.path.isfile(secrets_path):
try:
secrets = yaml.safe_load(open(secrets_path))
except Exception as e:
raise RuntimeError("Failed to open secrets configuration {0}: {1}".format(secrets_path, str(e)))
template = Template(template)
template = template.safe_substitute(secrets)
return ast.literal_eval(template)
示例6: load_secrets_file
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def load_secrets_file(config_dict: dict) -> dict:
from string import Template
import ast
secrets_path = dino_home + '/secrets/%s.yaml' % dino_env
# first substitute environment variables, which holds precedence over the yaml config (if it exists)
template = Template(str(config_dict))
template = template.safe_substitute(os.environ)
if os.path.isfile(secrets_path):
try:
secrets = yaml.safe_load(open(secrets_path))
except Exception as e:
raise RuntimeError("Failed to open secrets configuration {0}: {1}".format(secrets_path, str(e)))
template = Template(template)
template = template.safe_substitute(secrets)
return ast.literal_eval(template)
示例7: run
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def run(self, manual=False):
r = Run(report=self.report, name=self.name, manual=manual)
r.save()
logger = RunLineLogger(r)
try:
DB2_Query.set_logger(logger)
DB2_Query.connect()
q = DB2_Query()
q.query = string.Template(self.query)
artifact = q.result()
artifact.convert_to_unicode()
result = Result(run=r, name=self.name, table=artifact.to_dict() )
result.save()
r.success = True
r.save()
except Exception as e:
logger.log("ERROR: " + str(e) )
type_, value_, traceback_ = sys.exc_info()
logger.log( ",".join(traceback.format_tb( traceback_ )) )
return r
示例8: load_config
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def load_config(config, expand_env=False, force=False):
"""Return repos from a directory and fnmatch. Not recursive.
:param config: paths to config file
:type config: str
:param expand_env: True to expand environment varialbes in the config.
:type expand_env: bool
:param bool force: True to aggregate even if repo is dirty.
:returns: expanded config dict item
:rtype: iter(dict)
"""
if not os.path.exists(config):
raise ConfigException('Unable to find configuration file: %s' % config)
file_extension = os.path.splitext(config)[1][1:]
conf = kaptan.Kaptan(handler=kaptan.HANDLER_EXT.get(file_extension))
if expand_env:
with open(config, 'r') as file_handler:
config = Template(file_handler.read())
config = config.substitute(os.environ)
conf.import_config(config)
return get_repos(conf.export('dict') or {}, force)
示例9: add_mount
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def add_mount(self, device):
log = logger.get_logger('systemctl')
mount_template_file = join(self.platform_config.config_dir(), 'mount', 'mount.template')
mount_definition = Template(open(mount_template_file, 'r').read()).substitute({
'what': device,
'where': self.platform_config.get_external_disk_dir()
})
mount_filename = dir_to_systemd_mount_filename(self.platform_config.get_external_disk_dir())
with open(self.__systemd_file(mount_filename), 'w') as f:
f.write(mount_definition)
log.info('enabling {0}'.format(mount_filename))
check_output('systemctl enable {0} 2>&1'.format(mount_filename), shell=True)
self.__start(mount_filename)
示例10: __init__
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def __init__(self, detail=None, headers=None, comment=None,
body_template=None, **kw):
Response.__init__(self,
status='%s %s' % (self.code, self.title),
**kw)
Exception.__init__(self, detail)
if headers:
self.headers.extend(headers)
self.detail = detail
self.comment = comment
if body_template is not None:
self.body_template = body_template
self.body_template_obj = Template(body_template)
if self.empty_body:
del self.content_type
del self.content_length
示例11: write_config
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def write_config(wad, actions, episode_timeout):
"""
args:
wad: (str) name of corresponding wad file
actions: (str) list of available actions (default: "MOVE_FORWARD TURN_LEFT TURN_RIGHT")
"""
# open the file
filein = open(os.path.join(dir_path, 'config_template.txt'))
# read it
src = Template(filein.read())
mission_wad = os.path.splitext(os.path.basename(wad))[0]
d = {'actions': actions, 'mission_wad': mission_wad, 'episode_timeout': episode_timeout}
# do the substitution
result = src.substitute(d)
f = open(wad + ".cfg", "w+")
f.write(result)
f.close()
return wad + ".cfg"
示例12: translate
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def translate(self):
visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
# copy parts
for part in self.visitor_attributes:
setattr(self, part, getattr(visitor, part))
# get template string from file
try:
template_file = open(self.document.settings.template, 'rb')
except IOError:
template_file = open(os.path.join(self.default_template_path,
self.document.settings.template), 'rb')
template = string.Template(str(template_file.read(), 'utf-8'))
template_file.close()
# fill template
self.assemble_parts() # create dictionary of parts
self.output = template.substitute(self.parts)
示例13: load_principal_mappings
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def load_principal_mappings(neo4j_session, principal_mappings, node_label, relationship_name, update_tag):
map_policy_query = Template("""
UNWIND {Mapping} as mapping
MATCH (principal:AWSPrincipal{arn:mapping.principal_arn})
MATCH (resource:$node_label{arn:mapping.resource_arn})
MERGE (principal)-[r:$relationship_name]->(resource)
SET r.lastupdated = {aws_update_tag}
""")
if not principal_mappings:
return
map_policy_query = map_policy_query.safe_substitute(
node_label=node_label,
relationship_name=relationship_name,
)
neo4j_session.run(
map_policy_query,
Mapping=principal_mappings,
aws_update_tag=update_tag,
)
示例14: upload_ping
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def upload_ping(store, value, **kwargs):
"""Upload value to a given store"""
ping_key_template = Template('$submission_date/$source_name/'
'$source_version/$doc_type/$app/$channel/'
'$version/$build_id/$filename')
dimensions = {
'submission_date': '20160805',
'source_name': 'telemetry',
'source_version': '4',
'doc_type': 'saved_session',
'app': 'Firefox',
'channel': 'nightly',
'version': '51.0a1',
'build_id': '20160801074053',
'filename': uuid4()
}
dimensions.update(kwargs)
key = ping_key_template.substitute(**dimensions)
store.store[key] = value
示例15: _setParams
# 需要导入模块: import string [as 别名]
# 或者: from string import Template [as 别名]
def _setParams(self):
self.templateRequest = Template(self._rawTemplate)