Python string.Template() Examples

The following are 30 code examples for showing how to use string.Template(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 2
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 6 votes vote down vote up
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
Project: ConvLab   Author: ConvLab   File: spec_util.py    License: MIT License 6 votes vote down vote up
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 4
Project: restrain-jit   Author: thautwarm   File: cy_jit_ext_template.py    License: MIT License 6 votes vote down vote up
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 5
Project: dino   Author: thenetcircle   File: environ.py    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: dino   Author: thenetcircle   File: count_users_in_rooms.py    License: Apache License 2.0 6 votes vote down vote up
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 7
Project: dino   Author: thenetcircle   File: clear_db_online_table.py    License: Apache License 2.0 6 votes vote down vote up
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 8
Project: dino   Author: thenetcircle   File: kafka_to_rabbitmq.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: dino   Author: thenetcircle   File: clear_redis_cache.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: dino   Author: thenetcircle   File: clear_db_sessions_table.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: dino   Author: thenetcircle   File: count_users_in_rooms_loop.py    License: Apache License 2.0 6 votes vote down vote up
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 12
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 13
Project: git-aggregator   Author: acsone   File: config.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 14
Project: platform   Author: syncloud   File: systemctl.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 15
Project: pledgeservice   Author: MayOneUS   File: exc.py    License: Apache License 2.0 6 votes vote down vote up
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 16
Project: MazeExplorer   Author: microsoft   File: script_manipulator.py    License: MIT License 6 votes vote down vote up
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 17
Project: faces   Author: skarlekar   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 18
Project: cartography   Author: lyft   File: permission_relationships.py    License: Apache License 2.0 6 votes vote down vote up
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 19
Project: python_moztelemetry   Author: mozilla   File: test_spark.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 20
Project: httpninja   Author: irsdl   File: testcase_definition.py    License: Apache License 2.0 5 votes vote down vote up
def _setParams(self):
        self.templateRequest = Template(self._rawTemplate) 
Example 21
Project: httpninja   Author: irsdl   File: testcase_mutation.py    License: Apache License 2.0 5 votes vote down vote up
def asciiChar(HTTPRequestHolderObjs):
    result = []
    for HTTPRequestHolderObj in HTTPRequestHolderObjs:
        initHTTPReq = HTTPRequestHolderObj.rawHTTPRequest
        initAdditionalInfo = HTTPRequestHolderObj.additionalInfo
        for c in range(0, 256):
            asciiChar = chr(c)
            additionalInfo = 'ASCII [Code: {} - Char: {}]'.format(c, codecs.escape_encode(asciiChar))
            if initAdditionalInfo != '':
                additionalInfo = initAdditionalInfo + ' - ' + additionalInfo
            HTTPRequestHolderObjTemp = HTTPRequestHolder.HTTPRequestHolder(Template(initHTTPReq).safe_substitute(asciiChar=asciiChar),additionalInfo)
            result.append(HTTPRequestHolderObjTemp)
    return result 
Example 22
Project: httpninja   Author: irsdl   File: testcase_mutation.py    License: Apache License 2.0 5 votes vote down vote up
def asciiHex(HTTPRequestHolderObjs):
    result = []
    for HTTPRequestHolderObj in HTTPRequestHolderObjs:
        initHTTPReq = HTTPRequestHolderObj.rawHTTPRequest
        initAdditionalInfo = HTTPRequestHolderObj.additionalInfo
        for c in range(0, 256):
            asciiChar = chr(c)
            asciiHex = "{:02x}".format(c)
            additionalInfo = 'ASCII [Code: {} - Char: {} - Hex: {}]'.format(c, codecs.escape_encode(asciiChar), asciiHex)
            if initAdditionalInfo != '':
                additionalInfo = initAdditionalInfo + ' - ' + additionalInfo
            HTTPRequestHolderObjTemp = HTTPRequestHolder.HTTPRequestHolder(Template(initHTTPReq).safe_substitute(asciiHex=asciiHex),additionalInfo)
            result.append(HTTPRequestHolderObjTemp)
    return result 
Example 23
Project: httpninja   Author: irsdl   File: testcase_mutation.py    License: Apache License 2.0 5 votes vote down vote up
def unicodeChar(HTTPRequestHolderObjs):
    result = []
    for HTTPRequestHolderObj in HTTPRequestHolderObjs:
        initHTTPReq = HTTPRequestHolderObj.rawHTTPRequest
        initAdditionalInfo = HTTPRequestHolderObj.additionalInfo
        for u in range(0, 65535):
            unicodeChar = int2bytes(u)
            additionalInfo = 'UNICODE [Code: {} - Char: {}]'.format(u, codecs.escape_encode(unicodeChar))
            if initAdditionalInfo != '':
                additionalInfo = initAdditionalInfo + ' - ' + additionalInfo
            HTTPRequestHolderObjTemp = HTTPRequestHolder.HTTPRequestHolder(Template(initHTTPReq).safe_substitute(asciiChar=asciiChar),additionalInfo)
            result.append(HTTPRequestHolderObjTemp)
    return result 
Example 24
Project: httpninja   Author: irsdl   File: testcase_mutation.py    License: Apache License 2.0 5 votes vote down vote up
def encodingList(HTTPRequestHolderObjs):
    result = []
    charList = "IBM037,IBM437,IBM500,ASMO-708,DOS-720,ibm737,ibm775,ibm850,ibm852,IBM855,ibm857,IBM00858,IBM860,ibm861,DOS-862,IBM863,IBM864,IBM865,cp866,ibm869,IBM870,windows-874,cp875,shift_jis,gb2312,ks_c_5601-1987,big5,IBM1026,IBM01047,IBM01140,IBM01141,IBM01142,IBM01143,IBM01144,IBM01145,IBM01146,IBM01147,IBM01148,IBM01149,utf-16,unicodeFFFE,windows-1250,windows-1251,Windows-1252,windows-1253,windows-1254,windows-1255,windows-1256,windows-1257,windows-1258,Johab,macintosh,x-mac-japanese,x-mac-chinesetrad,x-mac-korean,x-mac-arabic,x-mac-hebrew,x-mac-greek,x-mac-cyrillic,x-mac-chinesesimp,x-mac-romanian,x-mac-ukrainian,x-mac-thai,x-mac-ce,x-mac-icelandic,x-mac-turkish,x-mac-croatian,utf-32,utf-32BE,x-Chinese-CNS,x-cp20001,x-Chinese-Eten,x-cp20003,x-cp20004,x-cp20005,x-IA5,x-IA5-German,x-IA5-Swedish,x-IA5-Norwegian,us-ascii,x-cp20261,x-cp20269,IBM273,IBM277,IBM278,IBM280,IBM284,IBM285,IBM290,IBM297,IBM420,IBM423,IBM424,x-EBCDIC-KoreanExtended,IBM-Thai,koi8-r,IBM871,IBM880,IBM905,IBM00924,EUC-JP,x-cp20936,x-cp20949,cp1025,koi8-u,iso-8859-1,iso-8859-2,iso-8859-3,iso-8859-4,iso-8859-5,iso-8859-6,iso-8859-7,iso-8859-8,iso-8859-9,iso-8859-13,iso-8859-15,x-Europa,iso-8859-8-i,iso-2022-jp,csISO2022JP,iso-2022-jp,iso-2022-kr,x-cp50227,euc-jp,EUC-CN,euc-kr,hz-gb-2312,GB18030,x-iscii-de,x-iscii-be,x-iscii-ta,x-iscii-te,x-iscii-as,x-iscii-or,x-iscii-ka,x-iscii-ma,x-iscii-gu,x-iscii-pa,utf-7,utf-8"
    charList = charList.split(",")
    for HTTPRequestHolderObj in HTTPRequestHolderObjs:
        initHTTPReq = HTTPRequestHolderObj.rawHTTPRequest
        initAdditionalInfo = HTTPRequestHolderObj.additionalInfo
        for charset in charList:
            additionalInfo = 'UNICODE [Charset: {}]'.format(charset)
            if initAdditionalInfo != '':
                additionalInfo = initAdditionalInfo + ' - ' + additionalInfo
            HTTPRequestHolderObjTemp = HTTPRequestHolder.HTTPRequestHolder(Template(initHTTPReq).safe_substitute(charset=charset),additionalInfo)
            result.append(HTTPRequestHolderObjTemp)
    return result 
Example 25
Project: myhdl   Author: myhdl   File: _toVerilog.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _writeFileHeader(f, fn, ts):
    vars = dict(filename=fn,
                version=myhdl.__version__,
                date=datetime.today().ctime()
                )
    if not toVerilog.no_myhdl_header:
        print(string.Template(myhdl_header).substitute(vars), file=f)
    if toVerilog.header:
        print(string.Template(toVerilog.header).substitute(vars), file=f)
    print(file=f)
    print("`timescale %s" % ts, file=f)
    print(file=f) 
Example 26
Project: myhdl   Author: myhdl   File: _toVHDL.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _writeFileHeader(f, fn):
    vars = dict(filename=fn,
                version=myhdl.__version__,
                date=datetime.today().ctime()
                )
    if toVHDL.header:
        print(string.Template(toVHDL.header).substitute(vars), file=f)
    if not toVHDL.no_myhdl_header:
        print(string.Template(myhdl_header).substitute(vars), file=f)
    print(file=f) 
Example 27
Project: myhdl   Author: myhdl   File: test_keywords.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_invalid_keyword_name():
    sig_1 = Signal(True)
    sig_2 = Signal(True)

    temp_directory = tempfile.mkdtemp()
    sys.path.append(temp_directory)

    keyword_template = string.Template(keyword_code)

    try:
        for keyword in _vhdl_keywords:
            if keyword in python_kwlist:
                continue

            fd, full_filename = tempfile.mkstemp(
                suffix='.py', dir=temp_directory)

            os.write(fd, keyword_template.substitute(keyword=keyword).encode('utf-8'))
            os.close(fd)

            module_name = os.path.basename(full_filename)[:-3]  # chop off .py
            keyword_import = importlib.import_module(module_name)

            a_block = keyword_import.invalid_import_keyword(sig_1, sig_2)

            with pytest.warns(ToVHDLWarning):
                a_block.convert(hdl='VHDL')

    finally:
        sys.path.pop()
        shutil.rmtree(temp_directory) 
Example 28
Project: myhdl   Author: myhdl   File: _extractHierarchy.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _interpolate(self):
        self._scrub_namespace()
        return string.Template(self.code).substitute(self.namespace) 
Example 29
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self, fmt):
        self._fmt = fmt or self.default_format
        self._tpl = Template(self._fmt) 
Example 30
Project: hiku   Author: vmagamedov   File: ui.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, root, engine, ctx=None, debug=False):
        self.root = root
        self.engine = engine
        self.ctx = ctx
        self.debug = debug
        self._console_html = string.Template(_decode(
            pkgutil.get_data('hiku.console', 'assets/console.html')
        ))
        self._docs_content = dumps_typedef(root)