本文整理汇总了Python中string.Template.split方法的典型用法代码示例。如果您正苦于以下问题:Python Template.split方法的具体用法?Python Template.split怎么用?Python Template.split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Template
的用法示例。
在下文中一共展示了Template.split方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_worker
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def start_worker(self, addr, port):
'''Must attempt to launch the specified worker. Should return the popen object for the new worker
or None, if the worker couldn't be be launched for some reason.'''
cmd_str = Template(OSQA_CMD_TEMPLATE_STR).substitute( \
addr = addr, \
port = str(port) \
)
self.logger.debug("cmd_str='%s'" % cmd_str)
cmd = cmd_str.split()
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutLogger = log.FileLoggerThread(self.logger, "osqa stdout", logging.INFO, process.stdout)
stderrLogger = log.FileLoggerThread(self.logger, "osqa stderr", logging.ERROR, process.stderr)
stdoutLogger.start()
stderrLogger.start()
return process
示例2: write_tmpl
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def write_tmpl(level, base, dir_, tmpls, config):
b = Template(base.replace('module', '$PROJECT_NAME'))
b = b.substitute(**config)
base_dir_list = b.split('/')
delim = base_dir_list.index('structure')
d = os.path.join('.', '/'.join(base_dir_list[delim + 1:]))
call(['mkdir', '-p', d])
for tmpl in tmpls:
if tmpl.endswith('py.tmpl'):
with open(os.path.join(base, tmpl), 'r') as f:
t = Template(f.read())
with open(os.path.join(d, tmpl[:-5]), 'w') as wf:
wf.write(t.substitute(**config))
elif tmpl.endswith('.py') or tmpl.endswith('.py.mako'):
call(['cp', os.path.join(base, tmpl), os.path.join(d, tmpl)])
示例3: start_worker
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def start_worker(self, addr, port):
'''Must attempt to launch the specified worker. Should return the popen object for the new worker
or None, if the worker couldn't be be launched for some reason.'''
cmd_str = Template(PHP_FCGI_CMD_TEMPLATE_STR).substitute( \
addr = addr, \
port = str(port) \
)
self.logger.debug("cmd_str='%s'" % cmd_str)
cmd = cmd_str.split()
environ = dict(os.environ.items() + [("MYSQL_USER", "user%d" % port)])
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env = environ)
stdoutLogger = log.FileLoggerThread(self.logger, "php5-cgi stdout", logging.INFO, process.stdout)
stderrLogger = log.FileLoggerThread(self.logger, "php5-cgi stderr", logging.ERROR, process.stderr)
stdoutLogger.start()
stderrLogger.start()
return process
示例4: generate_license
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def generate_license(self):
raw_license = Template(Templates.LicenseText).substitute(None)
copyrights = self._model.copyrights()
copyrights.sort()
license_block = []
license_block.append("/*")
for copyright in copyrights:
license_block.append(" * Copyright (c) %s" % copyright)
if len(copyrights) > 0:
license_block.append(" * ")
for line in raw_license.split('\n'):
license_block.append(" * " + line)
license_block.append(" */")
return '\n'.join(license_block)
示例5: run
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def run(command, **kwargs):
fail_hard = kwargs.pop("fail_hard", True)
# output to /dev/null by default:
kwargs.setdefault("stdout", open('/dev/null', 'w'))
kwargs.setdefault("stderr", open('/dev/null', 'w'))
command = Template(command).substitute(os.environ)
if "TRACE" in os.environ:
if 'cwd' in kwargs:
print("[cwd=%s] %s"%(kwargs['cwd'], command))
else: print(command)
try:
process = subprocess.Popen(command.split(' '), **kwargs)
process.wait()
except KeyboardInterrupt:
process.terminate()
raise
if process.returncode != 0 and fail_hard:
raise RunError("Failed: "+command)
return process.returncode
示例6: runCheck
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def runCheck():
execCommand = Template(jmeter_start_command).substitute(JMETER_HOME=jmeter_run_home, TEST_FILE=jmeter_run_test_file,
LOG=jmeter_run_log)
#Parse program arguments
args = execCommand.split()
#Set host and port to run jmeter against
jmeter_result_system_properties = ["-JSERVER_NAME=%s" % jmeter_run_host, "-JPORT=%s" % jmeter_run_port]
args[len(args):] = jmeter_result_internal_properties
args[len(args):] = jmeter_result_system_properties
#Run jmeter process
p = subprocess.Popen(args)
p.communicate()
returnCode = p.returncode
if returnCode :
print "UNKNOWN - Jmeter job ended not correctly. Return code - %s." % returnCode
sys.exit(STATUS_UNKNOWN)
示例7: _mkflinpreq
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def _mkflinpreq(self,series,START=None,END=None):
f = FLINPDICT
if len(series)>0:
s = series[0].split('/')
f['TIMESTAMP'] = ("%s" % datetime.now()).replace(' ','-').replace(':','.')
f['FAMIGLIA'] = "%- 12s" % s[0]
p = s[0]
f['NUM_CHIAVI']= "% 8d" % len(series)
f['MAXROW'] = "% 8d" % 20000
f['CHIAVI']=''
for ser in series:
s = ser.split('/')
if len(s) != 2:
raise ValueError('Manca il nome della famiglia in %s' % ser)
if s[0] != p:
raise ValueError('Nome della famiglia non coerente')
g = {}
g['LNG_CHIAVE'] = "% 3d" % len(s[1])
g['CHIAVE'] = "%- 99s" % s[1]
f['CHIAVI'] += Template(CHIAVIREQ).substitute(g)
f['LIMITS']=''
if START is not None:
f['LIMITS']=str("START "+START+"\n")
if END is not None:
f['LIMITS']=str(f['LIMITS']+"END "+END+"\n")
req = Template(FLINPREQ).substitute(f)
lines = req.split('\n')
W = 120
lines = [ line+' '*(W-len(line)) for line in lines ]
req = ''.join(lines)
return req.encode('ascii','ignore')
示例8: emitFuncDoc
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
#.........这里部分代码省略.........
fmtRowCol = 'column'
startIndex = 'startCol'
endIndex = 'endColPlusOne'
numIndices = 'numCols'
elif sparseFormat == 'CSR':
fmtColRow = 'column'
fmtRowCol = 'row'
startIndex = 'startRow'
endIndex = 'endRowPlusOne'
numIndices = 'numRows'
else:
raise ValueError ('Invalid sparse format "' + sparseFormat + '"')
if upLo == 'upper':
UpLo = 'Upper'
elif upLo == 'lower':
UpLo = 'Lower'
else:
raise ValueError ('Unknown upper/lower triangular designation "' + upLo + '"')
if dataLayout == 'row major':
colRow = 'row'
rowCol = 'column'
elif dataLayout == 'column major':
colRow = 'column'
rowCol = 'row'
else:
raise ValueError ('Unknown data layout "' + dataLayout + '"')
if unitDiag:
unitDiagStr = ' implicitly stored unit diagonal entries and'
else:
unitDiagStr = ''
if conjugateMatrixEntries:
briefConj = ',\n/// using conjugate of sparse matrix elements'
else:
briefConj = ''
substDict = {'sparseFormat': sparseFormat, 'UpLo': UpLo, 'upLo': upLo,
'unitDiagStr': unitDiagStr,
'colRow': colRow, 'rowCol': rowCol,
'briefConj': briefConj, 'numIndices': numIndices,
'startIndex': startIndex, 'endIndex': endIndex,
'fmtColRow': fmtColRow, 'fmtRowCol': fmtRowCol}
brief = '/// ${UpLo} triangular solve of a ${sparseFormat}-format sparse matrix\n'
brief = brief + '/// with ${colRow}-major input / output vectors\n'
if inPlace:
brief = brief + '/// (overwriting input with output)\n'
if unitDiag:
brief = brief + '/// and implicitly stored unit diagonal entries\n'
if conjugateMatrixEntries:
brief = brief + '/// using conjugate of sparse matrix entries\n'
body = '''///
/// \\tparam Ordinal The type of indices used to access the entries of
/// the sparse and dense matrices. Any signed or unsigned integer
/// type which can be used in pointer arithmetic with raw arrays
/// will do.
/// \\tparam MatrixScalar The type of entries in the sparse matrix.
/// This may differ from the type of entries in the input/output
/// matrices.'''
if not inPlace:
body = body + '\n' + \
'''/// \\tparam DomainScalar The type of entries in the input matrix Y.
/// This may differ from the type of entries in the output matrix X.'''
body = body + '\n' + \
'''/// \param numRows [in] Number of rows in the sparse matrix.
/// \param numCols [in] Number of columns in the sparse matrix.
/// \param numVecs [in] Number of columns in X.'''
if inPlace:
body = body + \
'\n/// \param X [in/out] Input/output multivector, stored in ${colRow}-major order.'
else:
body = body + \
'\n/// \param X [out] Output multivector, stored in ${colRow}-major order.'
body = body + '\n' + \
'''/// \param LDX [in] Stride between ${colRow}s of X. We assume unit
/// stride between ${rowCol}s of X.
/// \param ptr [in] Length (${numIndices}+1) array of index offsets
/// between ${fmtRowCol}s of the sparse matrix.
/// \param ind [in] Array of ${fmtColRow} indices of the sparse matrix.
/// ind[ptr[i] .. ptr[i+1]-1] are the ${fmtColRow} indices of row i
/// (zero-based) of the sparse matrix.
/// \param val [in] Array of entries of the sparse matrix.
/// val[ptr[i] .. ptr[i+1]-1] are the entries of ${fmtRowCol} i
/// (zero-based) of the sparse matrix.'''
if not inPlace:
body = body + '\n' + \
'''/// \param Y [in] Input multivector, stored in ${colRow}-major order.
/// \param LDY [in] Stride between ${colRow}s of Y. We assume unit
/// stride between ${rowCol}s of Y.'''
doc = Template(brief + body + '\n').substitute (substDict)
brief = '' # Release memory we don't need anymore
body = '' # Release memory we don't need anymore
# Indent each line.
return '\n'.join(' '*indent + line for line in doc.split('\n'))
示例9: vaporize
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
def vaporize(image_dir, make_mp4_instead_of_gif, img_types, audio_file = None):
# first get image type
dir_contents = listdir(image_dir)
image_type = None
if audio_file is None:
audio_file = choose(['x-files.ogg', 'short-macplus.mp3'])
for filename in dir_contents:
for some_type in img_types:
if filename.endswith(some_type):
image_type = some_type
break
if image_type is None:
print 'UNKNOWN IMAGE TYPE!'
return None
# add the `you decide` feature
# link a random yd[1-5] to image099.type to the proper directory
YOU_DECIDES = ['yd1', 'yd2', 'yd3', 'yd4', 'yd5']
# screw memory
yd_cmd = Template('cp ./you-decide/$ydn.$itp $idr/image00$l.$itp')
img_files = filter(lambda file: file.endswith(image_type) and file.startswith('image0'), dir_contents)
yd_cmd = yd_cmd.substitute(ydn = choose(YOU_DECIDES), itp = image_type, idr = image_dir, l = str(len(img_files) + 1))
print yd_cmd
call(yd_cmd.split(' '))
# optimize jp(e)gs
if img_types == 'jpeg' or image_type == 'jpg':
for img_file in img_files:
call(['jpegoptim', image_dir + '/' + img_file])
slideshow_cmd = Template('ffmpeg -framerate 1/2 -i $idr/image%03d.$itp -movflags faststart -c:v libx264 -pix_fmt yuv420p $idr/show.mp4')
# TODO: pipe `yes` for overwriting?
slideshow_cmd = '' + slideshow_cmd.substitute(idr = image_dir, itp = image_type)
result_cmd = None
result_path = None
if make_mp4_instead_of_gif:
result_cmd = Template('ffmpeg -i $idr/show.mp4 -i ./$adf -movflags faststart -strict -2 -vcodec copy $idr/final.mp4')
# result_path = image_dir + '/' + image_dir + '-' + 'final.mp4'
result_path = 'final.mp4'
else:
result_cmd = Template('ffmpeg -i $idr/show.mp4 $idr/final.gif')
# result_path = image_dir + '/' + image_dir + '-' + 'final.gif'
result_path = 'final.gif'
# TODO: pipe `yes` for overwriting?
result_cmd = '' + result_cmd.substitute(idr = image_dir, adf = audio_file)
call(slideshow_cmd.split(' '))
call(result_cmd.split(' '))
print '\n\n\n'
print slideshow_cmd
print result_cmd
print '\n\n\n'
return result_path
示例10: len
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import split [as 别名]
d['action'] = 'show his socks'
print s.substitute(x='slurm')
print s1.substitute(d)
print s1.safe_substitute(d1)
print '%-4s plus %+5s equals %s' % (1,2,3)
print 'with a moo-moo here, and a moo-moo there'.find('moo', 12, 100)
seq = ['1','2','3','4','5']
sep = '+'
s = sep.join(seq)
print sep.join(seq)
print 'AAAAAAAAAAA'.lower()
print 'sunqi'.replace('s','S')
print s.split('+')
print ' s un qi '.strip()
print ' s un qi '.strip(' sin')
from string import maketrans
table = maketrans('us','ka')
print len(table)
print 'translate: ' + str('sunuuuqi'.translate(table))
print 'translate: ' + str('sun u uu qi'.translate(table, ' '))
print table
print '---------------------chapter 4----------------------'
names = ['sunqi1', 'sunqi2', 'sunqi3', 'sunqi4']
nums = ['1', '2', '3', '4']
print nums[names.index('sunqi2')]