Python string.Template() Examples
The following are 30
code examples of string.Template().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
string
, or try the search function
.
Example #1
Source File: systemctl.py From platform with GNU General Public License v3.0 | 6 votes |
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)
Example #2
Source File: __init__.py From jawfish with MIT License | 6 votes |
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
Example #3
Source File: permission_relationships.py From cartography with Apache License 2.0 | 6 votes |
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, )
Example #4
Source File: spec_util.py From ConvLab with MIT License | 6 votes |
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
Example #5
Source File: test_spark.py From python_moztelemetry with Mozilla Public License 2.0 | 6 votes |
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
Example #6
Source File: download.py From gog-galaxy-plugin-downloader with GNU General Public License v3.0 | 6 votes |
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
Example #7
Source File: cy_jit_ext_template.py From restrain-jit with MIT License | 6 votes |
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))
Example #8
Source File: environ.py From dino with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: count_users_in_rooms.py From dino with Apache License 2.0 | 6 votes |
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)
Example #10
Source File: clear_db_online_table.py From dino with Apache License 2.0 | 6 votes |
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)
Example #11
Source File: kafka_to_rabbitmq.py From dino with Apache License 2.0 | 6 votes |
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)
Example #12
Source File: clear_redis_cache.py From dino with Apache License 2.0 | 6 votes |
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)
Example #13
Source File: clear_db_sessions_table.py From dino with Apache License 2.0 | 6 votes |
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)
Example #14
Source File: count_users_in_rooms_loop.py From dino with Apache License 2.0 | 6 votes |
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)
Example #15
Source File: __init__.py From faces with GNU General Public License v2.0 | 6 votes |
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)
Example #16
Source File: models.py From coursys with GNU General Public License v3.0 | 6 votes |
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
Example #17
Source File: script_manipulator.py From MazeExplorer with MIT License | 6 votes |
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"
Example #18
Source File: exc.py From pledgeservice with Apache License 2.0 | 6 votes |
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
Example #19
Source File: config.py From git-aggregator with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #20
Source File: dummy.py From bioforum with MIT License | 5 votes |
def get_template(self, template_name): tried = [] for template_file in self.iter_template_filenames(template_name): try: with open(template_file, encoding=settings.FILE_CHARSET) as fp: template_code = fp.read() except FileNotFoundError: tried.append(( Origin(template_file, template_name, self), 'Source does not exist', )) else: return Template(template_code) raise TemplateDoesNotExist(template_name, tried=tried, backend=self)
Example #21
Source File: wpRobot.py From psychsim with MIT License | 5 votes |
def explainDecision(decision,beliefs,mode): """ @param decision: the assessment of the safety of the given location (C{True} if safe, C{False} if dangerous) @type decision: bool @param location: the label of the location to which this recommendation applies @type location: str @param beliefs: a table of probabilities for the presence of different features at this location @type beliefs: strS{->}float @param mode: the type of explanation to give @type mode: str @return: a list of sentences @rtype: str[] """ result = [] result.append(Template(TEMPLATES['decision'][decision]).substitute(beliefs)) if 'confidence' in mode: result.append(Template(TEMPLATES['confidence'][decision]).substitute(beliefs)) if 'ability' in mode: result.append(Template(TEMPLATES['NBC'][beliefs['omega_NBCsensor']]).substitute(beliefs)) result.append(Template(TEMPLATES['armed'][beliefs['omega_camera']]).substitute(beliefs)) result.append(Template(TEMPLATES['microphone'][beliefs['omega_microphone']]).substitute(beliefs)) # for sensor in ['NBC','armed','microphone']: # result.append(Template(TEMPLATES[sensor][beliefs[sensor]]).substitute(beliefs)) if 'benevolence' in mode: result.append(Template(TEMPLATES['benevolence'][decision]).substitute(beliefs)) return result
Example #22
Source File: logger_base.py From loggers with GNU General Public License v2.0 | 5 votes |
def log(self, event, **kwargs): "append log info into log file" file_obj = open(self.log_file, 'a') #append new log infomation message_template = Template(self._log_str[event]) message = message_template.substitute(kwargs) append_ctnt = self._log_format % (message, '['+time.ctime()+']') file_obj.write(append_ctnt) file_obj.close()
Example #23
Source File: rule.py From rucio with Apache License 2.0 | 5 votes |
def generate_email_for_rule_ok_notification(rule, session=None): """ Generate (If necessary) an eMail for a rule with notification mode Y. :param rule: The rule object. :param session: The Database session """ session.flush() if rule.state == RuleState.OK and rule.notification == RuleNotification.YES: try: with open('%s/rule_ok_notification.tmpl' % config_get('common', 'mailtemplatedir'), 'r') as templatefile: template = Template(templatefile.read()) email = get_account(account=rule.account, session=session).email if email: text = template.safe_substitute({'rule_id': str(rule.id), 'created_at': str(rule.created_at), 'expires_at': str(rule.expires_at), 'rse_expression': rule.rse_expression, 'comment': rule.comments, 'scope': rule.scope.external, 'name': rule.name, 'did_type': rule.did_type}) add_message(event_type='email', payload={'body': text, 'to': [email], 'subject': '[RUCIO] Replication rule %s has been succesfully transferred' % (str(rule.id))}, session=session) except (IOError, NoOptionError): pass
Example #24
Source File: robot.py From psychsim with MIT License | 5 votes |
def explainDecision(decision,beliefs,mode,flag_check=''): """ @param decision: the assessment of the safety of the given location (C{True} if safe, C{False} if dangerous) @type decision: bool @param location: the label of the location to which this recommendation applies @type location: str @param beliefs: a table of probabilities for the presence of different features at this location @type beliefs: strS{->}float @param mode: the type of explanation to give @type mode: str @return: a list of sentences @rtype: str[] """ result = [] result.append(Template(TEMPLATES['general']['desc']).substitute(beliefs)) result.append(Template(TEMPLATES['decision'][decision]).substitute(beliefs)) if 'confidence' in mode: beliefs['flag'] = flag_check result.append(Template(TEMPLATES['confidence'][decision]).substitute(beliefs)) if 'ability' in mode: result.append(Template(TEMPLATES['NBC'][beliefs['omega_NBCsensor']]).substitute(beliefs)) result.append(Template(TEMPLATES['armed'][beliefs['omega_camera']]).substitute(beliefs)) result.append(Template(TEMPLATES['microphone'][beliefs['omega_microphone']]).substitute(beliefs)) # for sensor in ['NBC','armed','microphone']: # result.append(Template(TEMPLATES[sensor][beliefs[sensor]]).substitute(beliefs)) if 'benevolence' in mode: result.append(Template(TEMPLATES['benevolence'][decision]).substitute(beliefs)) return result
Example #25
Source File: dummy.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def from_string(self, template_code): return Template(template_code)
Example #26
Source File: dummy.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_template(self, template_name): for template_file in self.iter_template_filenames(template_name): try: with io.open(template_file, encoding=settings.FILE_CHARSET) as fp: template_code = fp.read() except IOError: continue return Template(template_code) else: raise TemplateDoesNotExist(template_name)
Example #27
Source File: dummy.py From bioforum with MIT License | 5 votes |
def from_string(self, template_code): return Template(template_code)
Example #28
Source File: glm_reporter.py From nistats with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _dmtx_to_svg_url(design_matrices): """ Accepts a FirstLevelModel or SecondLevelModel object with fitted design matrices & generates SVG Image URL, which can be inserted into an HTML template. Parameters ---------- design_matrices: List[pd.Dataframe] Design matrices computed in the model. Returns ------- svg_url_design_matrices: String SVG Image URL for the plotted design matrices, """ html_design_matrices = [] dmtx_template_path = os.path.join(HTML_TEMPLATE_ROOT_PATH, 'design_matrix_template.html' ) with open(dmtx_template_path) as html_template_obj: dmtx_template_text = html_template_obj.read() for dmtx_count, design_matrix in enumerate(design_matrices, start=1): dmtx_text_ = string.Template(dmtx_template_text) dmtx_plot = plot_design_matrix(design_matrix) dmtx_title = 'Session {}'.format(dmtx_count) plt.title(dmtx_title, y=0.987) dmtx_plot = _resize_plot_inches(dmtx_plot, height_change=.3) url_design_matrix_svg = plot_to_svg(dmtx_plot) # prevents sphinx-gallery & jupyter from scraping & inserting plots plt.close() dmtx_text_ = dmtx_text_.safe_substitute( {'design_matrix': url_design_matrix_svg, 'dmtx_title': dmtx_title, } ) html_design_matrices.append(dmtx_text_) svg_url_design_matrices = ''.join(html_design_matrices) return svg_url_design_matrices
Example #29
Source File: input.py From bob with GNU General Public License v3.0 | 5 votes |
def isRelocatable(self): """Returns True if the packages is relocatable.""" return self.__corePackage.recipe.isRelocatable() # FIXME: implement this on our own without the Template class. How to do proper # escaping?
Example #30
Source File: modules.py From paper-to-git with Apache License 2.0 | 5 votes |
def expand(template, extras, template_class=Template): """Expand the given template using the extras dictionary.""" substitutions = dict(extras) return template_class(template).safe_substitute(substitutions)