本文整理汇总了Python中string.ljust函数的典型用法代码示例。如果您正苦于以下问题:Python ljust函数的具体用法?Python ljust怎么用?Python ljust使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ljust函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: disassemble
def disassemble(co, lasti):
code = co.co_code
labels = findlabels(code)
n = len(code)
i = 0
while i < n:
c = code[i]
op = ord(c)
if op = SET_LINENO and i > 0: print # Extra blank line
if i = lasti: print '-->',
else: print ' ',
if i in labels: print '>>',
else: print ' ',
print string.rjust(`i`, 4),
print string.ljust(opname[op], 15),
i = i+1
if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256
i = i+2
print string.rjust(`oparg`, 5),
if op in hasconst:
print '(' + `co.co_consts[oparg]` + ')',
elif op in hasname:
print '(' + co.co_names[oparg] + ')',
elif op in hasjrel:
print '(to ' + `i + oparg` + ')',
print
示例2: writeMol2File
def writeMol2File(self, outFile, whichXyz=None):
'''writes the data to an already open file. don't close it.'''
if whichXyz is None:
whichXyz = range(self.xyzCount)
for oneXyz in whichXyz:
outFile.write("@<TRIPOS>MOLECULE\n")
if self.protName == "fake": #don't write fake
outFile.write(self.name + "\n")
else:
outFile.write(self.name + " " + self.protName + "\n")
outFile.write("%5d %5d %5d %5d %5d\n" % (len(self.atomNum), \
len(self.bondNum), 0, 0, 0))
outFile.write("SMALL\nUSER_CHARGES\n\n")
outFile.write("mmff94s_NoEstat = %5.2f\n" % self.inputEnergy[oneXyz])
outFile.write("@<TRIPOS>ATOM\n")
for oneAtom in xrange(len(self.atomNum)):
outFile.write( \
"%7d %6s % 8.4f % 8.4f % 8.4f %5s 1 <0> % 8.4f\n" % \
(self.atomNum[oneAtom], string.ljust(self.atomName[oneAtom], 6), \
self.atomXyz[oneXyz][oneAtom][0], \
self.atomXyz[oneXyz][oneAtom][1], \
self.atomXyz[oneXyz][oneAtom][2], \
string.ljust(self.atomType[oneAtom], 5), \
self.atomCharge[oneAtom]))
outFile.write("@<TRIPOS>BOND\n")
for oneBond in xrange(len(self.bondNum)):
outFile.write( \
"%6d%5d%5d %2s\n" % \
(self.bondNum[oneBond], self.bondStart[oneBond], \
self.bondEnd[oneBond], string.ljust(self.bondType[oneBond], 2)))
示例3: run_all
def run_all(self):
"""For each file in the test suite, run client program
assuming each file represents an individual test."""
try:
server = Server(self.ini["core"], self.ini["module"])
except Exception as e:
print e
raise RuntimeError("Unknown server: core = {0}, module = {1}".format(
self.ini["core"], self.ini["module"]))
if len(self.tests) == 0:
# noting to test, exit
return 0
server.deploy(self.ini["config"],
server.find_exe(self.args.builddir, silent=False),
self.args.vardir, self.args.mem, self.args.start_and_exit,
self.args.gdb, self.args.valgrind,
init_lua=self.ini["init_lua"], silent=False)
if self.args.start_and_exit:
print " Start and exit requested, exiting..."
exit(0)
longsep = "=============================================================================="
shortsep = "------------------------------------------------------------"
print longsep
print string.ljust("TEST", 48), "RESULT"
print shortsep
failed_tests = []
self.ini["server"] = server
for test in self.tests:
sys.stdout.write(string.ljust(test.name, 48))
# for better diagnostics in case of a long-running test
sys.stdout.flush()
test_name = os.path.basename(test.name)
if test_name in self.ini["disabled"]:
print "[ skip ]"
elif not server.debug and test_name in self.ini["release_disabled"]:
print "[ skip ]"
elif self.args.valgrind and test_name in self.ini["valgrind_disabled"]:
print "[ skip ]"
else:
test.run(server)
if not test.passed():
failed_tests.append(test.name)
print shortsep
if len(failed_tests):
print "Failed {0} tests: {1}.".format(len(failed_tests),
", ".join(failed_tests))
server.stop(silent=False)
server.cleanup()
if self.args.valgrind and check_valgrind_log(server.valgrind_log):
print " Error! There were warnings/errors in valgrind log file:"
print_tail_n(server.valgrind_log, 20)
return 1
return len(failed_tests)
示例4: write_data
def write_data(toolbox, data):
''' Opens the workbook, then the worksheet, then writes the data.'''
try:
workbook = excel.Workbooks.Open(toolbox)
except Exception as e:
print "Unable to instantiate workbook!"
print repr(e)
raise
if not workbook:
print "Unable to instantiate workbook!"
raise IOError("Workbook not found.")
try:
sheet = get_sheet('Inputs')
except Exception as e:
print "Unable to instantiate worksheet!"
print repr(e)
raise
if not sheet:
print "Unable to instantiate worksheet!"
raise IOError("Worksheet not found")
for k, d in data.items():
if d.cell:
print ('{}: writing value {} to cell {}'
''.format(ljust(k, 30), d.value, d.cell))
sheet.Range(d.cell).Value = d.value
else:
print ('{}: skipping value {}, no cell'
''.format(ljust(k, 30), d.value))
excel.Visible = True
示例5: report
def report(self, prefix="", emit=None):
if not emit:
emit = logging.info
if getattr(self, "source", None):
emit(prefix + "source : %s" % (self.source))
if getattr(self, "sink", None):
emit(prefix + "sink : %s" % (self.sink))
cur_time = time.time()
delta = cur_time - self.prev_time
c, p = self.cur, self.prev
x = sorted([k for k in c.iterkeys() if "_sink_" in k])
width_k = max([5] + [len(k.replace("tot_sink_", "")) for k in x])
width_v = max([20] + [len(str(c[k])) for k in x])
width_d = max([10] + [len(str(c[k] - p[k])) for k in x])
width_s = max([10] + [len("%0.1f" % ((c[k] - p[k]) / delta)) for k in x])
emit(prefix + " %s : %s | %s | %s"
% (string.ljust("", width_k),
string.rjust("total", width_v),
string.rjust("last", width_d),
string.rjust("per sec", width_s)))
verbose_set = ["tot_sink_batch", "tot_sink_msg"]
for k in x:
if k not in verbose_set or self.opts.verbose > 0:
emit(prefix + " %s : %s | %s | %s"
% (string.ljust(k.replace("tot_sink_", ""), width_k),
string.rjust(str(c[k]), width_v),
string.rjust(str(c[k] - p[k]), width_d),
string.rjust("%0.1f" % ((c[k] - p[k]) / delta), width_s)))
self.prev_time = cur_time
self.prev = copy.copy(c)
示例6: miscellaneous
def miscellaneous():
#
# alias
#
fp.write('#\n# Alias\n#\n')
results = db.sql('''
select alias,
cdate = convert(char(10), creation_date, 101)
from MRK_Alias_View where _Marker_key = %s
order by alias
''' % (markerKey), 'auto')
for r in results:
fp.write(string.ljust(r['alias'],30) + TAB)
fp.write(string.ljust(r['cdate'],15) + CRT)
#
# synonym
#
fp.write('#\n# Synonym\n#\n')
results = db.sql('''
select synonym,
cdate = convert(char(10), creation_date, 101)
from MGI_Synonym where _MGIType_key = 2 and _Object_key = %s
''' % (markerKey), 'auto')
for r in results:
fp.write(string.ljust(r['synonym'],30) + TAB)
fp.write(string.ljust(r['cdate'],15) + CRT)
示例7: short_help
def short_help(self):
help_str = "\nSupported modes are:\n"
mode_list = Mode.mode_list( )
for mode in mode_list:
aliases = mode.aliases()
s = ''
if aliases:
s += ' (%s)' % ', '.join( aliases )
lhs = '%s%s:' % (mode.__name__, s)
name_box = 15
name = string.ljust(lhs, name_box)
help = toolkit.boxed_string( mode.help(), 60 )
indent = string.ljust('', name_box+4)
indented_help = string.replace( help, '\n', '\n'+indent )
help_str = ( "%s %s%s\n"
% ( help_str, name, indented_help )
)
print ( "%s\nType '%s mode --help' for further help on a mode"
% ( help_str, self.get_prog_name() )
)
示例8: display
def display(self, cols):
# Create the maxCols list which represents the max
# length of each row element.
maxCols = []
for i in range(0, len(cols[0])):
maxCols.append(0)
for row in cols:
for i in range(0, len(row)):
if len(row[i]) > maxCols[i]:
maxCols[i] = len(row[i])
# Print the table using maxCols list to force all
# columns in the rows to line up. The first column
# (hostname) is left justified, and the subsequent
# columns are right justified.
for row in cols:
for i in range(0, len(row)):
if i == 0:
print string.ljust(row[i], maxCols[i]),
else:
print string.rjust(row[i], maxCols[i]),
if i < len(row)-1:
print '\t',
print
示例9: Point3DCoord
def Point3DCoord():
"show the coordinate of selected point"
pt = Point2D()
res = kcs_ui.point2D_req("请选择要查询的点", pt)
if res[0] == kcs_util.ok():
res = kcs_util.tra_coord_ship(pt.X, pt.Y, "")
if res[0] == 0:
pt3d = Point3D(res[1], res[2], res[3])
res, fr, fr_offset = kcs_util.coord_to_pos(1, pt3d.X)
res, lp_y, lp_y_offset = kcs_util.coord_to_pos(2, pt3d.Y)
res, lp_z, lp_z_offset = kcs_util.coord_to_pos(3, pt3d.Z)
fr_offset=round(fr_offset,2)
lp_y_offset=round(lp_y_offset,2)
lp_z_offset=round(lp_z_offset,2)
x=round(pt3d.X,2)
y=round(pt3d.Y,2)
z=round(pt3d.Z,2)
Msg("--"*25)
Msg("二维点:" + str(pt))
Msg("三维坐标信息:")
Msg("X: %s,FR%s %s" % (string.ljust(str(x), width), str(fr), _fmt(fr_offset)))
Msg("Y: %s,LP%s %s" % (string.ljust(str(y), width), str(lp_y), _fmt(lp_y_offset)))
Msg("Z: %s,LP%s %s" % (string.ljust(str(z), width), str(lp_z), _fmt(lp_z_offset)))
Msg("--"*25)
示例10: checkNumberOfRateRules
def checkNumberOfRateRules(rrInstance, testId):
print string.ljust ("Check " + testId, rpadding),
errorFlag = False
value = int (readLine())
if rrInstance.model.getNumRateRules() != value:
errorFlag = True
print passMsg (errorFlag)
示例11: GetValues
def GetValues(fullname):
# 把完整的项拆分成根项和子项两部分
name = string.split(fullname,'\\',1)
# 打开相应的项,为了让该函数更通用
# 使用了多个判断语句
if name[0] == 'HKEY_LOCAL_MACHINE':
key = RegOpenKey(HKEY_LOCAL_MACHINE,name[1], 0, KEY_READ)
elif name[0] == 'HKEY_CURRENT_USER':
key = RegOpenKey(HKEY_CURRENT_USER,name[1], 0, KEY_READ)
elif name[0] == 'HKEY_CLASSES_ROOT':
key = RegOpenKey(HKEY_CLASSES_ROOT,name[1], 0, KEY_READ)
elif name[0] == 'HKEY_CURRENT_CONFIG':
key = RegOpenKey(HKEY_CURRENT_CONFIG,name[1], 0, KEY_READ)
elif name[0] == 'HKEY_USERS':
key = RegOpenKey(HKEY_USERS,name[1], 0, KEY_READ)
else:
print 'err,no key named %s' (name[0])
# 查询项的项值数目
info = RegQueryInfoKey(key)
# 遍历项值获得项值数据
for i in range(0,info[1]):
ValueName = RegEnumValue(key, i)
# 调整项值名称长度,使输出更好看
print string.ljust(ValueName[0],20),ValueName[1]
# 关闭打开的项
RegCloseKey(key)
示例12: setAIPS
def setAIPS(self, fd, value):
"""
Write parameter value to AIPS TD file opened as fd
Inputs:
fd = open TD file positioned for write
value = data value dictionary
"""
################################################################
# Is this a "GO" parameter
code = self.AIPScode
if (code==' ') | (code=='*') | (code=='&') | (code=='$'):
myvalue = value[self.name] # extract value array from dictionary
# list and scalar separate
if myvalue.__class__==list: # List
# AIPS only supports float and strings
if self.type==float: # Float
for x in myvalue:
fd.write(struct.pack('f',x))
elif self.type==str: # String
for x in myvalue:
# Blank pad to proper length
xx = string.ljust(string.strip(x),self.dim[0])
fmt = str(self.dim[0])+'s'
fd.write(struct.pack(fmt,xx))
else: # Scalar
if self.type==float: # Float
fd.write(struct.pack('f',myvalue))
elif self.type==str: # String
# Blank pad to proper length
xx = string.ljust(string.strip(myvalue),self.dim[0])
fmt = str(self.dim[0])+'s'
fd.write(struct.pack(fmt,xx))
示例13: Atom2pdb
def Atom2pdb( atmobj ):
try:
if atmobj.valid != True: return ''
except:
return None
atm_type = ljust(str(atmobj.atm_type),6).upper()
atm_number = rjust(str(atmobj.atm_number),5)
if atmobj.atm_name[0].isdigit() and atmobj.atm_name[-1].isdigit(): atm_name = ' '+center(str(atmobj.atm_name),4).upper()
elif atmobj.atm_name[-1].isdigit(): atm_name = ' '+ljust(str(atmobj.atm_name),4).upper()
elif (atmobj.atm_name[-1] =='\''): atm_name = ' '+rjust(str(atmobj.atm_name),4).upper()
else: atm_name = ' '+center(str(atmobj.atm_name),4).upper()
alt_loc = center(str(atmobj.alt_loc),1)
resi_name = center(str(atmobj.resi_name),3).upper()+' '
chain = center(str(atmobj.chain),1).upper()
resSeq = rjust( str(atmobj.resSeq),4)
icode = center(str(atmobj.icode),1)+3*' '
pos = rjust( "%.3f" % atmobj.pos[0],8)+rjust("%.3f" % atmobj.pos[1],8)+rjust("%.3f" % atmobj.pos[2], 8)
occ = rjust( str(atmobj.occ), 6)
bfac = rjust( str(atmobj.bfac),5) + 11*' '
elem = center( str(atmobj.elem),2)
charge = center(str(atmobj.charge),2)
return atm_type + atm_number + atm_name + alt_loc+ resi_name + chain + resSeq + icode + pos + occ + bfac + elem + charge+'\n'
示例14: __str__
def __str__(self):
# display process details (OLD, doesn't show many details)
c = string.ljust(self.comm, 20)
u = string.ljust(self.user, 10)
t = string.ljust(self.time, 10)
return( '%s\t%s\t%s\t%s\t%s\t%s' % (self.pid, u, c, t, self.pcpu, self.s) )
示例15: print_items
def print_items(self, max_items):
import os
import string
from findtorrent.core.colors import colors
from hurry.filesize import size, si
cols = int(os.popen('stty size', 'r').read().split()[1])
print colors.HEADER + \
'No. Name' + (cols - 33) * ' ' + 'Size Files Seed Leech'
print cols * '-'
for index, item in enumerate(Items.sorted):
if (max_items != -1 and index + 1 > max_items):
break
print colors.INDEX + string.ljust(str(index + 1) + '.', 5) + \
colors.NAME + string.ljust(item['name'][:cols - 31],
cols - 31) + \
colors.SIZE + string.rjust(size(item['size'],
system=si), 6) + \
colors.FILES + string.rjust(str(item['files']) \
.replace('-1', 'N/A'), 7) + \
colors.SEED + string.rjust(str(item['seed']) \
.replace('-1', 'N/A'), 6) + \
colors.LEECH + string.rjust(str(item['leech']) \
.replace('-1', 'N/A'), 7) + \
colors.ENDC