python类Template()的实例源码

test_pep292.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_delimiter_override(self):
        eq = self.assertEqual
        raises = self.assertRaises
        class AmpersandTemplate(Template):
            delimiter = '&'
        s = AmpersandTemplate('this &gift is for &{who} &&')
        eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
        raises(KeyError, s.substitute)
        eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
        eq(s.safe_substitute(), 'this &gift is for &{who} &')
        s = AmpersandTemplate('this &gift is for &{who} &')
        raises(ValueError, s.substitute, dict(gift='bud', who='you'))
        eq(s.safe_substitute(), 'this &gift is for &{who} &')

        class PieDelims(Template):
            delimiter = '@'
        s = PieDelims('@who likes to eat a bag of @{what} worth $100')
        self.assertEqual(s.substitute(dict(who='tim', what='ham')),
                         'tim likes to eat a bag of ham worth $100')
__init__.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
bootstrap.py 文件源码 项目:landscape-client 作者: CanonicalLtd 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def bootstrap(self, **vars):
        path = Template(self.path).substitute(**vars)
        self._create(path)

        if self.mode is not None:
            os.chmod(path, self.mode)

        if os.getuid() == 0:
            if self.username is not None:
                uid = pwd.getpwnam(self.username).pw_uid
            else:
                uid = -1

            if self.group is not None:
                gid = grp.getgrnam(self.group).gr_gid
            else:
                gid = -1

            if uid != -1 or gid != -1:
                os.chown(path, uid, gid)
server.py 文件源码 项目:chordspeak 作者: nyboer 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def chord():
    chords = request.args.get('transcript')
    confidence = request.args.get('confidence')

    '''do midi stuff with chord request'''
    t = Template("request='${chords}' (${confidence})")

    str = t.substitute({"chords": chords, "confidence": confidence})
    print("========================================")
    print(str)
    print("========================================")

    resp = parser(chords)

    print json.dumps(resp, indent=4, sort_keys=True)

    chord = Chord()
    chord.getchord()

    for note in resp['notes']:
        chord.getchord(note['note'], note['params'][0], resp['octave'])

    chord.play()

    return json.dumps(resp)
cli.py 文件源码 项目:zalando-deploy-cli 作者: robin-wittler 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def copy_template(template_path: Path, path: Path, variables: dict):
    for d in template_path.iterdir():
        target_path = path / d.relative_to(template_path)
        if d.is_dir():
            copy_template(d, target_path, variables)
        elif target_path.exists():
            # better not overwrite any existing files!
            raise click.UsageError('Target file "{}" already exists. Aborting!'.format(target_path))
        else:
            with Action('Writing {}..'.format(target_path)):
                target_path.parent.mkdir(parents=True, exist_ok=True)
                with d.open() as fd:
                    contents = fd.read()
                template = string.Template(contents)
                contents = template.safe_substitute(variables)
                with target_path.open('w') as fd:
                    fd.write(contents)
util.py 文件源码 项目:calcit 作者: cstein 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def substitute_file(from_file, to_file, substitutions):
    """ Substitute contents in from_file with substitutions and
        output to to_file using string.Template class

        Raises: IOError file the file to replace from is not found

        Arguments:
        ----------
        from_file -- template file to load
        to_file -- substituted file
        substitutions -- dictionary of substitutions.
    """
    with open(from_file, "r") as f_in:
        source = string.Template(f_in.read())

        with open(to_file, "w") as f_out:
            outcome = source.safe_substitute(substitutions)
            f_out.write(outcome)
mpc.py 文件源码 项目:dotfiles 作者: maotora 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def playlistinfo(self, sortkey='pos'):
        """Shows playlist information sorted by key
        """
        new_buf = wc.buffer_search("", "mpc: playlist")
        if len(new_buf) == 0:
            new_buf = wc.buffer_new('mpc: playlist', "", "", "", "")

        pl = self._mpdc.playlistinfo()
        try:
            # Numerical sort
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(int(x), int(y)),
                         key=itemgetter(sortkey))
        except ValueError:
            # Alpha sort
            lcmp = lambda x,y: cmp(x.lower(), y.lower())
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(x.lower(), y.lower()),
                         key=itemgetter(sortkey))

        t = Template(wc.config_get_plugin("playinfo"))
        for line in spl:
            wc.prnt(new_buf, t.safe_substitute(line))

        return pl
mpc.py 文件源码 项目:dotfiles 作者: maotora 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def playlistinfo(self, sortkey='pos'):
        """Shows playlist information sorted by key
        """
        new_buf = wc.buffer_search("", "mpc: playlist")
        if len(new_buf) == 0:
            new_buf = wc.buffer_new('mpc: playlist', "", "", "", "")

        pl = self._mpdc.playlistinfo()
        try:
            # Numerical sort
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(int(x), int(y)),
                         key=itemgetter(sortkey))
        except ValueError:
            # Alpha sort
            lcmp = lambda x,y: cmp(x.lower(), y.lower())
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(x.lower(), y.lower()),
                         key=itemgetter(sortkey))

        t = Template(wc.config_get_plugin("playinfo"))
        for line in spl:
            wc.prnt(new_buf, t.safe_substitute(line))

        return pl
zenias_functions.py 文件源码 项目:zenias-python 作者: DevBlend 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def z_make_templates(source, target, replacements):
    for f in os.listdir(source):
        newtarget = os.path.join(target, f)
        newsource = os.path.join(source, f)
        if os.path.isdir(newsource):
            os.makedirs(newtarget)
            print z_info('Created folder ' + f)
            z_make_templates(newsource, newtarget, replacements)
        else:
            targetfile = io.open(newtarget, 'w')
            sourcefile = io.open(newsource, 'r')
            for line in sourcefile:
                template = Template(line)
                targetfile.write(template.substitute(replacements))
            targetfile.close()
            print z_info('Created file ' + f)


# Merge two dicts recursively.
# Values from y will override the ones from x
# Returns x or y if the other is empty.
setup.py 文件源码 项目:gitpwnd 作者: nccgroup 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _add_file_to_c2_repo(config, template_file_path, params, dest_path_in_c2_repo):
    with open(template_file_path, 'r') as f:
        templatized_file = string.Template(f.read())

    dest_file = os.path.join(config["benign_repo_path"], dest_path_in_c2_repo)

    with open(dest_file, "w") as f:
        f.write(templatized_file.safe_substitute(params))

    # Add file to the c2 repo
    orig_dir = os.path.abspath(os.curdir)
    # cd into cloned git repo to do git munging there
    os.chdir(config["benign_repo_path"])

    if "nothing to commit" not in str(subprocess.check_output("git status", shell=True)):
        # Add agent.py and push
        subprocess.check_output("git add %s" % dest_path_in_c2_repo, shell=True)
        subprocess.check_output("git commit -m 'Add %s'" % dest_path_in_c2_repo, shell=True)
        subprocess.check_output("git push --repo %s" % config["primary_clone_url"], shell=True)

    os.chdir(orig_dir)
core.py 文件源码 项目:BAG_framework 作者: ucb-art 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _parse_yaml_file(fname):
    # type: (str) -> Dict[str, Any]
    """Parse YAML file with environment variable substitution.

    Parameters
    ----------
    fname : str
        yaml file name.

    Returns
    -------
    table : Dict[str, Any]
        the yaml file as a dictionary.
    """
    content = read_file(fname)
    # substitute environment variables
    content = string.Template(content).substitute(os.environ)
    return yaml.load(content)
StandaloneExtension.py 文件源码 项目:pytorch 作者: tylergenter 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_wrapper_template(self, declaration):
        arg_desc = []

        def describe_arg(arg):
            desc = self.TYPE_NAMES[arg['type']] + ' ' + arg['name']
            if arg.get('nullable'):
                return '[{} or None]'.format(desc)
            return desc
        for option in declaration['options']:
            option_desc = [describe_arg(arg)
                           for arg in option['arguments']
                           if not arg.get('ignore_check', False)]
            if option_desc:
                arg_desc.append('({})'.format(', '.join(option_desc)))
            else:
                arg_desc.append('no arguments')
        arg_desc.sort(key=len)
        arg_desc = ['"' + desc + '"' for desc in arg_desc]
        arg_str = ', '.join(arg_desc)
        return Template(self.WRAPPER_TEMPLATE.safe_substitute(expected_args=arg_str))
configurator.py 文件源码 项目:Home-Assistant 作者: jmart518 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_html():
    if DEV:
        try:
            with open("dev.html") as fptr:
                html = Template(fptr.read())
                return html
        except Exception as err:
            print(err)
            print("Delivering embedded HTML")
    return INDEX
ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def html(self):
        # ????????
        form_html = ''
        if self.form_def is not None:
            form_html = self.form_def.render(self.data, self._template, self.edit_fields, self.omit_fields, self.errors, **self.options)
            for widget in self._widgets:
                form_html += widget.html()
            buttons = self.form_def.buttons(self._buttons)

        else:
            fields_html = {}
            for widget in self._widgets:
                if isinstance(widget, hidden_input):
                    form_html += widget.html()
                else:
                    fields_html[widget.name] = widget.html()
            if not self._template: self.layout()
            form_html += Template(self._template).safe_substitute(fields_html)
            buttons = self._gen_buttons_html(self._buttons)

        if 'submit' in self._triggers:
            kss_url = self._triggers['submit'][0][0]
        else:
            kss_url = ''

        klass = ' '.join(self.klass)
        if kss_url:
            klass += ' KSSLoad'
            loading_data = 'data-loading="%s"' % self.loading_text
        else:
            loading_data = ''

        desc, h3 = '', ''
        if self.title: h3 = '<h3>%s</h3>' % self.title
        if self.description: desc = '<div class="discreet m_b_3">%s</div>' % self.description
        if self._layout == 'inline':
            return '''<form action="%s" %s class="%s" method="post">%s%s<table style="width: 100%%"><tr><td>%s</td><td>%s</td></tr></table>%s</form>''' % \
                (kss_url or self.action, loading_data, klass, h3, desc, form_html, buttons, self.hidden_input)
        else:
            return '''<form action="%s" %s class="%s" method="post">%s%s%s%s%s</form>''' % \
                    (kss_url or self.action, loading_data, klass, h3, desc, form_html, buttons, self.hidden_input)
config.py 文件源码 项目:skipper 作者: Stratoscale 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))
LKEvernoteApi.py 文件源码 项目:pythonista-scripts 作者: lukaskollmer 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def append_to_note(guid, new_content, main_new_content, add_if_already_exists):

    #Get the note to be updated using the note's guid http://dev.evernote.com/documentation/reference/NoteStore.html#Fn_NoteStore_getNote
    note_store = _get_note_store()

    log_progress('load the \'2Archive\' note')
    note = note_store.getNote(guid, True, True, False, False)

    #Regular expressions used to replicate ENML tags.  These same tags will be used to "rebuild" the note with the existing note metadata
    log_progress('do the regEx stuff')
    xmlTag          = re.search('<\?xml.*?>', note.content).group()
    docTag          = re.search('<\!DOCTYPE.*?>', note.content).group()
    noteOpenTag     = re.search('<\s*en-note.*?>', note.content).group()
    noteCloseTag    = re.search('<\s*/en-note.*?>', note.content).group()
    breakTag        = '<br />'

    #Rebuild the note using the new content
    log_progress('Rebuild the note using the new content')
    content           =  note.content.replace(xmlTag, "").replace(noteOpenTag, "").replace(noteCloseTag, "").replace(docTag, "").strip()

    if main_new_content in content:
        if add_if_already_exists:
            content += breakTag + "".join(new_content)
        else:
            log_progress('url already in note')
    else:
        content += breakTag + ''.join(new_content)
    template          =  Template ('$xml $doc $openTag $body $closeTag')
    note.content      =  template.substitute(xml=xmlTag,doc=docTag,openTag=noteOpenTag,body=content,closeTag=noteCloseTag)

    #Update the note

    log_progress('save the updated note to evernote')
    try:
        _get_note_store().updateNote(note)
    except:
        print sys.exc_info()

    #Return updated note (object) to the function
    return note
input.py 文件源码 项目:bob 作者: BobBuildTool 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _getStates(self):
        return self.__corePackage.states


# FIXME: implement this on our own without the Template class. How to do proper
# escaping?
input.py 文件源码 项目:bob 作者: BobBuildTool 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def resolve(self, text):
        if isinstance(text, str):
            resolver = IncludeHelper.Resolver(self.__fileLoader, self.__baseDir, self.__varBase, text)
            t = Template(text)
            t.delimiter = '$<'
            t.pattern = self.__pattern
            ret = t.substitute(resolver)
            sourceAnchor = "_BOB_SOURCES[$LINENO]=" + quote(self.__sourceName)
            return ("\n".join(resolver.prolog + [sourceAnchor, ret]), "\n".join(resolver.incDigests))
        else:
            return (None, None)
init.py 文件源码 项目:shub-image 作者: scrapinghub 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def cli(project, base_image, base_deps, add_deps, requirements):
    project_dir = utils.get_project_dir()
    scrapy_config = shub_utils.get_config()
    if not scrapy_config.has_option('settings', project):
        raise shub_exceptions.BadConfigException(
            'Settings for the project is not found')
    settings_module = scrapy_config.get('settings', project)
    values = {
        'base_image':   base_image,
        'system_deps':  _format_system_deps(base_deps, add_deps),
        'system_env':   _format_system_env(settings_module),
        'requirements': _format_requirements(project_dir, requirements),
    }
    values = {key: value if value else '' for key, value in values.items()}
    source = Template(DOCKERFILE_TEMPLATE.strip())
    results = source.substitute(values)
    results = results.replace('\n\n', '\n')

    click.echo("The following Dockerfile will be created:\n{}".format(results))
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    while True:
        dockefile_path = os.path.join(project_dir, 'Dockerfile')
        choice = input("Save to {}: (y/n)".format(dockefile_path)).lower()
        if choice in valid:
            if valid[choice]:
                with open(dockefile_path, 'w') as dockerfile:
                    dockerfile.write(results)
                click.echo('Saved.')
            break
        click.echo("Please respond with 'yes'('y') or 'no'(n)")


问题


面经


文章

微信
公众号

扫码关注公众号