本文整理汇总了Python中string.Template.encode方法的典型用法代码示例。如果您正苦于以下问题:Python Template.encode方法的具体用法?Python Template.encode怎么用?Python Template.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Template
的用法示例。
在下文中一共展示了Template.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: describe2latex
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def describe2latex(study_info, stats):
"""Function to translate the descriptions of the variables to latex.
TODO
----
- crete a plot folder
- get paths to save figures
"""
## 0. Needed variables
this_dir, this_filename = os.path.split(os.path.abspath(__file__))
if not os.path.exists(join(study_info['path'], 'Plots')):
os.mkdir(join(study_info['path'], 'Plots'))
header = built_header()
title = built_title(study_info)
content = built_content(study_info, stats)
## 1. Applying to the template
templ_fl = join(this_dir, '../data/templates/tex/document_template.txt')
file_ = open(templ_fl, "r")
filecode = file_.read()
filetext = Template(filecode).safe_substitute(header=header, title=title,
content=content)
filetext = filetext.encode('utf-8')
return filetext
示例2: aws_run_instance
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def aws_run_instance():
# TODO: * IAM role cannot be set.
ami_map = {
# 'ap-southeast-2': 'ami-862211e5', # docker enabled amazon
'ap-southeast-2': 'ami-5c8fb13f', # arch linux
}
image = ami_map[BASE_CONFIG['aws_region']]
sg_id = aws_get_security_group_id()
# creds = aws_profile()
secret_key = gen_secret()
with tempfile.NamedTemporaryFile() as outf:
with open('boilerplate/scripts/arch-user-data.sh') as inf:
data = Template(inf.read()).substitute(
prod_cfg(),
# **creds,
secret_key=secret_key
)
outf.write(data.encode())
outf.flush()
res = run_cfg('$aws ec2 run-instances'
' --image-id $image'
' --key-name $project'
' --security-group-ids "{sg_id}"'
' --user-data file://{user_data}'
' --instance-type t2.micro'
' --iam-instance-profile Name=ec2-profile'
' --associate-public-ip-address'
' --count 1'.format(user_data=outf.name, sg_id=sg_id),
image=image, capture=True, dev=False)
res = json.loads(res)
return res['Instances'][0]['InstanceId']
示例3: noteflightEmbed
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def noteflightEmbed(outputStream):
'''
Takes in a stream outputStream, and a string title. Returns the HTML for a page
containing a noteflight
flash embed of the stream and the title title
TODO: Change javascript and noteflight embed to relate to be server-specific
>>> sc = corpus.parse('bwv7.7').measures(0, 2)
>>> (output, contentType) = alpha.webapps.templates.noteflightEmbed(sc)
>>> contentType
'text/html; charset=utf-8'
'''
from music21.musicxml import m21ToXml
musicxmlBytes = m21ToXml.GeneralObjectExporter().parse(outputStream)
musicxmlString = musicxmlBytes.decode('utf-8')
musicxmlString = musicxmlString.replace('\n', '')
musicxmlString = musicxmlString.replace('\'', '\\\'')
htmlStr = """
<html>
<head>
<title>Music21 URL App Response</title>
<script language="javascript"
src="http://web.mit.edu/music21/webapps/client/javascript/music21.js"></script>
<script>
// Event handling function
function noteflightEventHandler(e)
{
if(e.type == 'scoreDataLoaded') {
m21.noteflight.sendMusicXMLToNoteflightEmbed('nfscore', '$musicxml')
}
}
</script>
<script language="javascript">
m21 = new Music21interface();
function setup() {
m21.noteflight.createNoteflightEmbed('noteflightembed', 'nfscore',
'fc79df30896da6aa03f90ff771015913ca6880be',800, 450, 1.0);
}
</script>
</head>
<body onload="setup()">
<h1>Music21 Output</h1>
<div id="noteflightembed">
</div>
</body>
</html>
"""
htmlData = Template(htmlStr)
htmlData = htmlData.safe_substitute(musicxml=musicxmlString)
return (htmlData.encode('utf-8'), 'text/html; charset=utf-8')
示例4: __init__
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def __init__(self, **kwargs):
# create a temp file to hold a list of all the directories
try:
cmd = 'ls > .dirs_list.tmp'
popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
out = popen.communicate()
except:
print("There was an error creating the temp file")
return
# get the total number of directories with HPL.dat files, so we know how big
# to make the slurm array
dirs = []
for (dirpath, dirnames, filenames) in os.walk('.'):
dirs.extend(dirnames) # only get directories, not files
array_size = len(dirs)
kwargs['array_size'] = array_size
# set memory to a MB number instead of GB
kwargs['mem'] = int(kwargs['mem'])*1000
# create the output directory where all the slurm log files will go
try:
os.mkdir('output')
except:
print("folder 'output' exists")
sbatch = Template('''#!/bin/bash
#SBATCH --partition=$queue
#SBATCH --time=$hours:00:00
#SBATCH -o $root_dir/output/hpl_test_%j.log
#SBATCH --job-name=hpl_tester
#SBATCH --ntasks=$ntasks
#SBATCH --workdir=$root_dir
#SBATCH --mem=$mem
#SBATCH --array=1-$array_size
# grab line # SLURM_ARRAY_TASK_ID from dirs_list.tmp
HPL_DAT_DIR=$$(sed -n "$$SLURM_ARRAY_TASK_ID"p .dirs_list.tmp)
# cd into the directory
cd $root_dir/$$HPL_DAT_DIR
echo "This is array task $$SLURM_ARRAY_TASK_ID"
echo "should be in directory $$HPL_DAT_DIR"
srun --mpi=pmi2 xhpl
''')
for key,value in kwargs.items():
setattr(self, key, value)
sbatch = sbatch.substitute(dict(**kwargs))
print('Submitting *****{\n%s\n}*****' % sbatch)
popen = subprocess.Popen('sbatch', shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
out = popen.communicate(sbatch.encode())[0].strip() #e.g. something like "Submitted batch job 209"
print("Slurm batch output: %s" % out)
示例5: aws_register_task_definition
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def aws_register_task_definition(family):
# TODO: Check if secret key is already set, if not, generate one.
with tempfile.NamedTemporaryFile() as outf:
with open('./scripts/{}-task-definition.json'.format(family)) as inf:
data = Template(inf.read()).substitute(prod_cfg())
outf.write(data.encode())
outf.flush()
run_cfg('$aws ecs register-task-definition'
' --cli-input-json file://{}'.format(outf.name))
示例6: start
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def start(self, user):
html = u'''<!html >
<head>
<title>Sarakste ar $user</title>
<meta http-equiv="Content-Type" value="text/html; charset=utf-8" />
</head>
<body>
<h1>$user</h1>
'''
self.user = stringify_user(user)
html = Template(html).substitute(user = self.user)
self.handle.write(html.encode("utf-8"))
示例7: generate_release_notes
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def generate_release_notes(project):
artifact_signature = helpers.sign_file(project.image_path(), project.update_signing_keyfile())
attrs = dict()
attrs['version'] = project.build_version()
attrs['changelog'] = generate_changelog(project)
attrs['signature'] = "" if artifact_signature == None else "DMG Signature: %s" % (artifact_signature)
template_source = open(project.release_notes_tmpl(), 'r').read()
release_notes_text = Template(template_source).substitute(attrs)
with open(project.release_notes_file(), 'w') as release_notes_file:
release_notes_file.write(release_notes_text.encode('utf-8'))
示例8: execute
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def execute(self):
env = self.state.document.settings.env
try:
out_dir = os.environ["DIAGRAMS_DIR"]
except:
raise RuntimeError("The '.. diagram::' directive requires a DIAGRAMS_DIR environment variable to be set.")
try:
dot_executable = os.environ["DOT_EXECUTABLE"]
except KeyError:
self.add_rst(".. figure:: /images/ImageNotFound.png\n\n" +
" graphviz not found - diagram could not be rendered.")
return []
#Make sure we have an output directory
if not os.path.exists(out_dir):
os.makedirs(out_dir)
diagram_name = self.arguments[0]
if diagram_name[-4:] != ".dot":
raise RuntimeError("Diagrams need to be referred to by their filename, including '.dot' extension.")
in_path = os.path.join(env.srcdir, "diagrams", diagram_name)
out_path = os.path.join(out_dir, diagram_name[:-4] + ".png")
#Generate the diagram
try:
in_src = open(in_path, 'r').read()
except:
raise RuntimeError("Cannot find dot-file: '" + diagram_name + "' in '" + os.path.join(env.srcdir,"diagrams"))
out_src = Template(in_src).substitute(STYLE)
if PY3:
out_src = out_src.encode()
gviz = subprocess.Popen([dot_executable,"-Tpng","-o",out_path], stdin=subprocess.PIPE)
gviz.communicate(input=out_src)
gviz.wait()
#relative path to image, in unix style
rel_path = os.path.relpath(out_path, env.srcdir).replace("\\","/")
self.add_rst(".. image:: /" + rel_path + "\n\n")
return []
示例9: html_template
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def html_template(body, metadata):
try:
template_text = open(metadata["templatefile"]).read()
except IOError:
error = "<html><body>Template file ('%r') not found.</body></html>"
return error % metadata["templatefile"]
try:
css = open(metadata["cssfile"]).read()
except IOError:
error = "<html><body>CSS file ('%r') not found.</body></html>"
return error % metadata["cssfile"]
from string import Template
metadata = metadata.copy() #no side effects, i guess
metadata["body"] = body
metadata["css"] = Template(css).safe_substitute(metadata)
r = Template(template_text).safe_substitute(metadata)
return r.encode("UTF-8")
示例10: __enter__
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def __enter__(self):
self.mesh_pre = [NamedTemporaryFile(suffix='.STL') for i in self.meshes]
self.mesh_post = NamedTemporaryFile(suffix='.STL')
self.script_out = NamedTemporaryFile()
# export the meshes to a temporary STL container
for m, f in zip(self.meshes, self.mesh_pre):
m.export(file_type='stl', file_obj=f.name)
self.replacement = {'mesh_' + str(i) : m.name for i,m in enumerate(self.mesh_pre)}
self.replacement['mesh_pre'] = str([i.name for i in self.mesh_pre])
self.replacement['mesh_post'] = self.mesh_post.name
self.replacement['script'] = self.script_out.name
script_text = Template(self.script).substitute(self.replacement)
self.script_out.write(script_text.encode('utf-8'))
self.script_out.flush()
return self
示例11: scad_interface
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def scad_interface(meshes, script):
'''
A way to interface with openSCAD which is itself an interface
to the CGAL CSG bindings.
CGAL is very stable if difficult to install/use, so this function provides a
tempfile- happy solution for getting the basic CGAL CSG functionality.
Arguments
---------
meshes: list of Trimesh objects
script: string of the script to send to scad.
Trimesh objects can be referenced in the script as
$mesh_0, $mesh_1, etc.
'''
mesh_out = [NamedTemporaryFile(suffix='.STL') for i in meshes]
mesh_in = NamedTemporaryFile(suffix='.STL')
script_out = NamedTemporaryFile(suffix='.scad')
# export the meshes to a temporary STL container
for m, f in zip(meshes, mesh_out):
m.export(file_type='stl', file_obj=f.name)
replacement = {'mesh_' + str(i) : m.name for i,m in enumerate(mesh_out)}
script_text = Template(script).substitute(replacement)
script_out.write(script_text.encode('utf-8'))
script_out.flush()
# run the SCAD binary
check_call(['openscad',
script_out.name,
'-o',
mesh_in.name])
# bring the SCAD result back as a Trimesh object
mesh_in.seek(0)
mesh_result = load_stl(mesh_in)
# close all the freaking temporary files
mesh_in.close()
script_out.close()
for f in mesh_out:
f.close()
return mesh_result
示例12: write
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def write(self, message,):
html = u'''<div>$type $user</div>
<div>$time</div>
<div>$subject</div>
<div>$text</div>'''
if message['type'] == 'inbox':
type = u'no'
message['user'] = stringify_user(message['user'])
else:
type = u'kam'
message['user'] = self.user
html = Template(html).substitute(user = message['user'],
time = datetime.datetime.fromtimestamp(int(message['timestamp'])).isoformat(),
subject = message['title'],
text = message['text'],
type = type)
self.handle.write(html.encode("utf-8"))
示例13: aws_create_role
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def aws_create_role(name=None, policies=[]):
name = name if name is not None else '$project'
# Create the role.
run_cfg('$aws iam create-role --role-name %s'
' --assume-role-policy-document'
' file://boilerplate/scripts/ecs-assume-role.json' % name)
# Add policies to the role.
for policy in policies:
with tempfile.NamedTemporaryFile() as outf:
with open('./scripts/%s.json' % policy) as inf:
data = Template(inf.read()).substitute(prod_cfg(), name=name)
outf.write(data.encode())
outf.flush()
print(data)
run_cfg('$aws iam put-role-policy --role-name %s'
' --policy-name %s'
' --policy-document file://%s' %
(name, policy, outf.name))
示例14: translate
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def translate(self):
"""
Return the translated message. If the original is a string object,
the return value is a string object. If it is a unicode object,
the return value is a unicode object.
"""
message = self.message
if self.domain is None:
# Map the translated string with given parameters
if type(self.mapping) is dict:
if isinstance(message, unicode) :
message = message.encode('utf-8')
message = Template(message).substitute(self.mapping)
else:
from Products.ERP5.ERP5Site import getSite
request = Globals.get_request()
translation_service = getGlobalTranslationService()
if self.mapping:
unicode_mapping = {}
for k, v in self.mapping.iteritems():
if isinstance(v, str):
v = v.decode('utf-8')
unicode_mapping[k] = v
else:
unicode_mapping = self.mapping
translated_message = translation_service.translate(
self.domain,
message,
mapping=unicode_mapping,
context=getSite(request),
default=self.default)
if translated_message is not None:
message = translated_message
if isinstance(self.message, str):
if isinstance(message, unicode):
message = message.encode('utf-8')
elif isinstance(message, str):
message = message.decode('utf-8')
return message
示例15: _createPrivmsg
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import encode [as 别名]
def _createPrivmsg(self, channel, payload, event, hidden=None):
bold = ircutils.bold
format_ = self.plugin.registryValue('format.%s' % event, channel)
if not format_.strip():
return
repl = flatten_subdicts(payload)
for (key, value) in dict(repl).items():
if key.endswith('url'):
repl[key + '__tiny'] = self._shorten_url(value)
elif key.endswith('ref'):
repl[key + '__branch'] = value.split('/', 2)[2]
elif isinstance(value, str):
repl[key + '__firstline'] = value.split('\n', 1)[0]
s = Template(format_).safe_substitute(repl)
if hidden is not None:
s += _(' (+ %i hidden commits)') % hidden
if sys.version_info[0] < 3:
s = s.encode('utf-8')
return ircmsgs.privmsg(channel, s)