本文整理汇总了Python中string.Template.safe_substitute方法的典型用法代码示例。如果您正苦于以下问题:Python Template.safe_substitute方法的具体用法?Python Template.safe_substitute怎么用?Python Template.safe_substitute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Template
的用法示例。
在下文中一共展示了Template.safe_substitute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: writeLocalesTargetFile
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def writeLocalesTargetFile(args, states, transitions):
stateFragmentTplStr = """
// _COMMENT: (state) $name : $desc
$i18n = _("$id");"""
stateFragmentTpl = Template(stateFragmentTplStr)
activityFragmentTplStr = """
// _COMMENT: (activity) $name : $activity
$i18n = _("${id}_activity");"""
activityFragmentTpl = Template(activityFragmentTplStr)
transitionFragmentTplStr = """
// _COMMENT: (transition) $name : $desc
$i18n = _("$id");"""
transitionFragmentTpl = Template(transitionFragmentTplStr)
fragments = ["<?php"]
for state in states:
fragments.append(stateFragmentTpl.safe_substitute(state))
if('activity' in state):
fragments.append(activityFragmentTpl.safe_substitute(state))
for transition in transitions:
fragments.append(transitionFragmentTpl.safe_substitute(transition))
locales = "".join(fragments)
#FIXME: tricky hack for python 2 and 3 compatibility
if sys.version_info < (2, 8):
locales = locales.encode('utf-8')
targetFile = open(args.localesTargetFile, 'w')
targetFile.write(locales)
targetFile.close()
示例2: generateFile
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def generateFile(fname, params):
"""Returns the generated file body
fname - The file name to write to
params - The params past in
[1] label/name
[2] object name
"""
file_path = '%s/%s' % (getTemplateDir(), fname,)
try:
f = open(file_path, 'r')
except:
logger.critical('Unable to open %s' % (file_path,))
sys.exit(-1)
template = Template(f.read())
f.close()
body = template.safe_substitute(name=params[1], label=params[1],
api_version=getApiVersion())
if (len(params) == 3):
template = Template(body)
body = template.safe_substitute(object=params[2])
return body
示例3: _createspec
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def _createspec(self, tar_filename):
# Creates a spec file and returns the path
template_str = self._read_template()
rpmbuild_env = self._create_rpmbuild_env()
if self.requires is None:
requires_line = ""
else:
requires_line = "Requires: %s" % (self.requires)
d = dict(application=self.application, source=tar_filename,
requires=requires_line, version=self.version,
release=self.release, license=self.license,
install_dir=self.install_dir, arch=self.arch)
s = Template(template_str)
s.safe_substitute(d)
spec_path = "%s/%s.spec" % (self.rpmbuild_env['specs'], self.application)
f = open(spec_path , 'w')
f.write(s.safe_substitute(d))
f.close()
return spec_path
示例4: do_pastebin_json
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def do_pastebin_json(self, s):
"""Upload to pastebin via json interface."""
url = urljoin(self.config.pastebin_url, '/json/new')
payload = {
'code': s,
'lexer': 'pycon',
'expiry': self.config.pastebin_expiry
}
self.interact.notify(_('Posting data to pastebin...'))
try:
response = requests.post(url, data=payload, verify=True)
response.raise_for_status()
except requests.exceptions.RequestException as exc:
self.interact.notify(_('Upload failed: %s') % (str(exc), ))
return
self.prev_pastebin_content = s
data = response.json()
paste_url_template = Template(self.config.pastebin_show_url)
paste_id = urlquote(data['paste_id'])
paste_url = paste_url_template.safe_substitute(paste_id=paste_id)
removal_url_template = Template(self.config.pastebin_removal_url)
removal_id = urlquote(data['removal_id'])
removal_url = removal_url_template.safe_substitute(removal_id=removal_id)
self.prev_pastebin_url = paste_url
self.interact.notify(_('Pastebin URL: %s - Removal URL: %s') %
(paste_url, removal_url))
return paste_url
示例5: paste
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def paste(self, s):
"""Upload to pastebin via json interface."""
url = urljoin(self.url, '/json/new')
payload = {
'code': s,
'lexer': 'pycon',
'expiry': self.expiry
}
try:
response = requests.post(url, data=payload, verify=True)
response.raise_for_status()
except requests.exceptions.RequestException as exc:
raise PasteFailed(exc.message)
data = response.json()
paste_url_template = Template(self.show_url)
paste_id = urlquote(data['paste_id'])
paste_url = paste_url_template.safe_substitute(paste_id=paste_id)
removal_url_template = Template(self.removal_url)
removal_id = urlquote(data['removal_id'])
removal_url = removal_url_template.safe_substitute(
removal_id=removal_id)
return (paste_url, removal_url)
示例6: __init__
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def __init__(self):
InstallCommand.__init__(self)
self.cron_acl_sudo = "#!/bin/sh"
with open(files.get_rel_path("data/cron_acl.tpl")) as f:
cron_acl_tpl = Template(f.read())
self.cron_acl_sudo = cron_acl_tpl.safe_substitute(group="sudo", site_path="/data/www")
self.cron_acl_dev_team = "#!/bin/sh"
if CONFIG.is_set('site','ldap_dev_team'):
with open(files.get_rel_path("data/cron_dev_team.tpl")) as f:
cron_acl_tpl = Template(f.read())
self.cron_acl_dev_team = cron_acl_tpl.safe_substitute(group=CONF_MAP('site','ldap_dev_team'))
self.packages = "acl"
self.add_package(self.packages)
self.add_folder('/etc/cron.acl')
self.add_file('/etc/crontab',
ck_func=self.check_acl_crontab,
fix_func=self.fix_acl_crontab)
self.add_file('/etc/cron.acl/sudo',
ck_func=self.check_perm_cron,
fix_func=self.fix_perm_cron,
perm={'u':'rx', 'g':'rx', 'o':'rx'})
self.add_file('/etc/cron.acl/ldap_dev_team',
ck_func=self.check_perm_dev_team,
fix_func=self.fix_perm_dev_team,
perm={'u':'rx', 'g':'rx', 'o':'rx'})
示例7: Main
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def Main():
cart = []
cart.append(dict(Item="Burger", Price=4, Qty=2))
cart.append(dict(Item="Wings", Price=5, Qty=8))
cart.append(dict(Item="Iced Tea", Price=3, Qty=1))
cart.append(dict(Item="Coke Float", Price=2, Qty=1))
t = Template("$Qty * $Item = $Price")
for data in cart:
print t.substitute(data)
print ""
# Using Safe substitute and not defining $Sr
t = Template("$Sr $Qty * $Item = $Price")
for data in cart:
print t.safe_substitute(data)
print ""
# Changed Delimiter
t = MyTemplate("#Qty * #Item = #Price")
for data in cart:
print t.substitute(data)
print ""
cart = []
cart.append(dict(Item="Ham", Price=4, Qty=2))
cart.append(dict(Item="Fish", Price=5, Qty=8))
cart.append(dict(Item="Chicken", Price=3, Qty=8))
# Using {} braces for placeholder
t = Template("$Qty * ${Item}burger = $Price")
for data in cart:
print t.safe_substitute(data)
示例8: create
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def create(self, params=None, userId=None, userEmail=None):
Log.debug('create')
""" sends data to RT System """
if not userId: userId = params['login']
type = ReleaseType().getById(params['type'])
uri = '%s%s/ticket/new'%(getSettings('rt.domain'), getSettings('rt.path'))
body = Template("""Project:
$project
Environment:
$environment
Release Date:
$releaseDate
Version:
$version
Rollback:
$rollback
Properties:
$properties
Notes:
$notes
""")
ticket = Template("""id: ticket/new
Queue: $q_name
Requestor: $req_email
Subject: $subject
Cc: $cc_email
Owner: $owner
Status: $status
Priority: $priority
Starts: $starts
Text: $content""")
data = dict({
'q_name': 'General',
'status': 'new',
'req_email': userEmail,
'cc_email': params['mailer'],
'subject': '%s (%s) to [%s]'%(type.label, params['project'], params['environment'].upper()),
'owner': '',
'priority': '',
'starts': params['releaseDate'],
'content': body.safe_substitute(params)
})
data = {'user': userId, 'pass': params['password'], 'content': ticket.safe_substitute(data)}
Log.debug('==== data [%s]'%(data))
Log.debug('==== uri [%s]'%(uri))
try:
code, content = self._sendToRT(uri, data)
try: rt_id = findall("Ticket (\d+) created", content)[0]
except IndexError: print 'Unknown RT ID'; sys.exit()
Log.debug('==== rt_id [%s]'%(rt_id))
return rt_id
except urllib2.URLError:
print 'Failed to get Authenticated Session'
sys.exit()
示例9: generate_spec
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def generate_spec(options, tmpl, channel):
data = {
"channel": channel,
"system": platform.system().lower(),
"machine": platform.machine().lower(),
"dist": get_dist(),
"directory_name": get_directory_name(),
}
dist = get_dist()
if dist == "redhat" or dist == "centos":
dist = platform.dist()
major = dist[1].split(".")[0]
distro = dist[0]
if re.search("redhat-6", data["directory_name"]):
data["directory_name"] = "redhat-6-x86_64"
elif re.search("redhat-7", data["directory_name"]):
data["directory_name"] = "redhat-7-x86_64"
elif re.search("redhat-5", data["directory_name"]):
data["directory_name"] = "redhat-5-x86_64"
elif re.search("centos-5", data["directory_name"]):
data["directory_name"] = "centos-5-x86_64"
elif re.search("centos-6", data["directory_name"]):
data["directory_name"] = "centos-6-x86_64"
elif re.search("centos-7", data["directory_name"]):
data["directory_name"] = "centos-7-x86_64"
# http://bugs.centos.org/view.php?id=5197
# CentOS 5.7 identifies as redhat
if int(major) <= 5 and distro == "redhat":
f = open("/etc/redhat-release")
new_dist = f.read().lower().split(" ")[0]
if new_dist == "centos":
distro = "centos"
if major == "5":
data["key"] = "centos-5.asc"
else:
data["key"] = "linux.asc"
elif dist == "fedora":
data["key"] = "linux.asc"
if options.get("distribution"):
data["directory_name"] = options["distribution"]
tmpl = Template(tmpl)
spec = open(SPEC_FMT % channel, "w")
spec.write(tmpl.safe_substitute(data))
spec.close()
repo_in = open(REPO_IN % channel).read()
tmpl = Template(repo_in)
repo = open(REPO_FMT % channel, "w")
repo.write(tmpl.safe_substitute(data))
repo.close()
示例10: get_build_cmd
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def get_build_cmd(self):
"""Return command used for building source for this distribution
Substitutions are done in the command strings:
$d => The distro's name
$a => the target architecture
$p => the package's name
$v => the package's version
$j => rebuildd job id
"""
# Strip epochs (x:) away
try:
index = self.package.version.index(":")
args = { 'd': self.dist, 'a': self.arch, \
'v': self.package.version[index+1:], 'p': self.package.name, \
'j': str(self.id) }
t = Template(RebuilddConfig().get('build', 'build_cmd'))
return t.safe_substitute(**args)
except ValueError:
pass
try:
args = { 'd': self.dist, 'a': self.arch, \
'v': self.package.version, 'p': self.package.name, \
'j': str(self.id) }
t = Template(RebuilddConfig().get('build', 'build_cmd'))
return t.safe_substitute(**args)
except TypeError, error:
RebuilddLog.error("get_build_cmd has invalid format: %s" % error)
return None
示例11: request4SyncAPI
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def request4SyncAPI(self, api_name):
self.method = self.conf.get(api_name, "method")
#request_bodyの構築と変数の整形
if(self.conf.has_option(api_name,"request_body")):
self.request_body = self.conf.get(api_name, "request_body")
#reqeust bodyの整形
self.request_body = self.request_body.replace('\\','')
template_body = Template(self.request_body) #Temaplateによる識別子の変換
self.request_body = template_body.safe_substitute(self.common.get_data())
#commondataによる変換
request_body_obj = json.loads(self.request_body)
self.request_body = json.dumps(self.common.pull(request_body_obj))
else: #request_bodyが指定されなかったときの情報
self.request_body = ""
#pathの構築と変数の整形
if(self.conf.has_option(api_name,"path")):
self.path = self.conf.get(api_name,"path")
template_path = Template(self.path)
self.path = template_path.safe_substitute(self.ids)
else:
self.path = ""
self.showRequest()
self.response = self.connect(self.method, self.request_url,self.path,self.request_body,self.headers)
self.showResponse(self.response)
#commondataへのデータの引き継ぎ
self.push_commondata(json.loads(self.response["entity"]))
self.common.show()
示例12: get_page
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def get_page(environ, start_response, message1='', message2=''):
''' Returns page as string. '''
page_template = \
Template(open(os.path.join(gui_path,'page_template.htm')).read())
# Start response as html page
start_response('200 OK', [('Content-Type', 'text/html')])
# Get name of page requested, replacing '' with index
page_name = environ['PATH_INFO'][1:]
if page_name == '':
page_name = 'index'
# Check if txt file with body for page exists, if so get as Template
try:
page_path = os.path.join(gui_path, page_name + '.txt')
page_body = Template(open(page_path).read())
except: # If page not found, get error page
page_path = os.path.join(gui_path, '404.txt')
page_body = Template(open(page_path).read())
# Substitute filepath first, then pagebody and localport
page_body_f = str(page_body.safe_substitute(message1=message1,
message2=message2))
return page_template.safe_substitute(pagebody=page_body_f,
localport=localport)
示例13: _generate_zsh
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def _generate_zsh(self, opt_values, pos_args):
# deal with doit commands
cmds_desc = []
cmds_args = []
for name in sorted(self.cmds):
cmd_class = self.cmds[name]
cmd = cmd_class(**self.init_kwargs)
cmds_desc.append(" '{0}: {1}'".format(cmd.name, cmd.doc_purpose))
cmds_args.append(self._zsh_cmd_args(cmd))
template_vars = {
'pt_bin_name': sys.argv[0].split('/')[-1],
'pt_cmds':'\n '.join(cmds_desc),
'pt_cmds_args':'\n'.join(cmds_args),
}
if opt_values['hardcode_tasks']:
self.task_list, _ = self.loader.load_tasks(
self, opt_values, pos_args)
lines = []
for task in self.task_list:
if not task.is_subtask:
lines.append("'{0}: {1}'".format(task.name, task.doc))
template_vars['pt_tasks'] = '(\n{0}\n)'.format('\n'.join(lines))
else:
tmp_tasks = Template(
'''("${(f)$($pt_bin_name list --template '{name}: {doc}')}")''')
template_vars['pt_tasks'] = tmp_tasks.safe_substitute(template_vars)
template = Template(zsh_start)
self.outstream.write(template.safe_substitute(template_vars))
示例14: generate_thematic_schema
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def generate_thematic_schema(self,):
# setup sqlite connection
conn = sqlite3.connect(self.thematic_sqlite)
# load spatialite extension
conn.enable_load_extension(True)
cmd = "SELECT load_extension('libspatialite')"
cur = conn.cursor()
cur.execute(cmd)
geom_types = {"points": "POINT", "lines": "LINESTRING", "polygons": "MULTIPOLYGON"}
# create and execute thematic sql statements
sql_tmpl = Template(
"CREATE TABLE $tablename AS SELECT osm_id, $osm_way_id $columns, Geometry FROM $planet_table WHERE $select_clause"
)
recover_geom_tmpl = Template("SELECT RecoverGeometryColumn($tablename, 'GEOMETRY', 4326, $geom_type, 'XY')")
for layer, spec in self.thematic_spec.iteritems():
layer_type = layer.split("_")[-1]
isPoly = layer_type == "polygons"
osm_way_id = ""
# check if the thematic tag is in the jobs tags, if not skip this thematic layer
if not spec["key"] in self.tags[layer_type]:
continue
if isPoly:
osm_way_id = "osm_way_id,"
params = {
"tablename": layer,
"osm_way_id": osm_way_id,
"columns": ", ".join(self.tags[layer_type]),
"planet_table": spec["table"],
"select_clause": spec["select_clause"],
}
sql = sql_tmpl.safe_substitute(params)
cur.execute(sql)
geom_type = geom_types[layer_type]
recover_geom_sql = recover_geom_tmpl.safe_substitute(
{"tablename": "'" + layer + "'", "geom_type": "'" + geom_type + "'"}
)
conn.commit()
cur.execute(recover_geom_sql)
cur.execute("SELECT CreateSpatialIndex({0}, 'GEOMETRY')".format("'" + layer + "'"))
conn.commit()
# remove existing geometry columns
cur.execute("SELECT DiscardGeometryColumn('planet_osm_point','Geometry')")
cur.execute("SELECT DiscardGeometryColumn('planet_osm_line','Geometry')")
cur.execute("SELECT DiscardGeometryColumn('planet_osm_polygon','Geometry')")
conn.commit()
# drop existing spatial indexes
cur.execute("DROP TABLE idx_planet_osm_point_GEOMETRY")
cur.execute("DROP TABLE idx_planet_osm_line_GEOMETRY")
cur.execute("DROP TABLE idx_planet_osm_polygon_GEOMETRY")
conn.commit()
# drop default schema tables
cur.execute("DROP TABLE planet_osm_point")
cur.execute("DROP TABLE planet_osm_line")
cur.execute("DROP TABLE planet_osm_polygon")
conn.commit()
cur.close()
示例15: normalize_brew_name
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import safe_substitute [as 别名]
def normalize_brew_name(filename):
"""
input: a path to a brew library, as returned by otool, that can have this form :
- an absolute path /usr/local/lib/yyy
output:
a tuple (brewlib, abspath, rpath) where:
- brewlib is the name of the brew lib
- abspath is the absolute path of the qt lib inside the app bundle of exepath
- relpath is the correct rpath to a qt lib inside the app bundle
"""
GlobalConfig.logger.debug("normalize_brew_name({0})".format(filename))
brewlib_name_rgx = re.compile(BREWLIB_REGEX)
rgxret = brewlib_name_rgx.match(filename)
if not rgxret:
msg = "couldn't normalize a brew lib filename: {0}".format(filename)
GlobalConfig.logger.critical(msg)
raise Exception(msg)
# brewlib normalization settings
brewlib = rgxret.groups()[0]
templ = Template(BREWLIB_NORMALIZED)
# from brewlib, forge 2 path :
# - absolute path of qt lib in bundle,
abspath = os.path.normpath(
templ.safe_substitute(prefix=os.path.dirname(GlobalConfig.exepath) + "/..", brewlib=brewlib)
)
# - and rpath containing @executable_path, relative to exepath
rpath = templ.safe_substitute(prefix="@executable_path/..", brewlib=brewlib)
GlobalConfig.logger.debug("\treturns({0})".format((brewlib, abspath, rpath)))
print filename, "->", brewlib, abspath, rpath
return brewlib, abspath, rpath