本文整理汇总了Python中string.rsplit函数的典型用法代码示例。如果您正苦于以下问题:Python rsplit函数的具体用法?Python rsplit怎么用?Python rsplit使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rsplit函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_code
def generate_code(self):
FOLDER = "C:\Users\saikumar\workspace\Nand2Tetris\\07\\"
file_name = string.rsplit(self._parser.get_filename(), '.', 1)[0]
file_object = open(FOLDER + file_name + '.asm', 'w')
# for eq, gt, lt we have to use control flow
# once it sets required result back to stack
jump_sequence = 0
for line in self._parser.get_line():
code_fragment = string.rsplit(line, ' ', 1)
# Memory Access Instruction
if len(code_fragment) == 2:
assembly_code = CodeWriter.VM_STACK_COMMANDS[code_fragment[0]]
assembly_code = string.replace(assembly_code, 'X', code_fragment[1])
file_object.write(assembly_code)
elif len(code_fragment) == 1:
if code_fragment[0] in ['add', 'sub', 'or', 'not', 'and', 'neg']:
assembly_code = CodeWriter.VM_STACK_COMMANDS[code_fragment[0]]
file_object.write(assembly_code)
elif code_fragment[0] in ['eq', 'gt', 'lt']:
assembly_code = CodeWriter.VM_STACK_COMMANDS[code_fragment[0]]
assembly_code = string.replace(assembly_code, '_J', '_' + str(jump_sequence))
file_object.write(assembly_code)
jump_sequence += 1
file_object.write('(END)\n' +\
'@END\n' +\
'0;JMP'
)
示例2: run
def run(self):
PATH = "E:\\Nand2Tetris\\nand2tetris\\projects\\08\\FunctionCalls\\FibonacciElement"
PATH = os.path.abspath(PATH)
if os.path.isdir(PATH):
file_name = string.rsplit(PATH, "\\", 1)[1]
code_writer = CodeWriter(PATH=PATH)
print "The path is directory " + PATH
code_writer.set_filename(file_name + ".asm")
code_writer.start_up_code()
vm_files = [f for f in os.listdir(PATH) if f.find(".vm") > 0]
if "Sys.vm" in vm_files:
sysindex = vm_files.index("Sys.vm")
vm_files[0], vm_files[sysindex] = vm_files[sysindex], vm_files[0]
for file_name in vm_files:
print file_name
parser = Parser(file_name, PATH)
parser.first_scan()
code_writer.set_parser(parser)
code_writer.generate_code()
code_writer.terminate_code()
else:
print "The path is file " + PATH
PATH, file_name = string.rsplit(PATH, "\\", 1)
parser = Parser(file_name, PATH)
parser.first_scan()
code_writer = CodeWriter(PATH=PATH)
code_writer.set_parser(parser)
code_writer.set_filename(string.rsplit(file_name, ".", 1)[0] + ".asm")
code_writer.start_up_code()
code_writer.generate_code()
code_writer.terminate_code()
示例3: fetch_testfiles
def fetch_testfiles(self):
"""Needed flash files, sis-files and testscripts from given matti scripts -folder are added to file list."""
tmp_case_list = []
# tmp_image_list = []
os.chdir(os.path.normpath(self.configuration.matti_scripts))
try:
for path, _, names in os.walk(os.getcwd()):
for name in names:
if re.search(r'.*?[.]rb\Z', name):
tmp_case_list.append((os.path.normpath(os.path.join(path, name)), os.path.join("ats3", "matti", "script", name)))
if tmp_case_list:
for tmp_case in tmp_case_list:
self.configuration.step_list.append(dict(path=os.path.join("§TEST_RUN_ROOT§", str(tmp_case[1])), name="Test case"))
if self.configuration.flash_images:
for image in self.configuration.flash_images:
tmp = string.rsplit(image, os.sep)
image_name = tmp[len(tmp)-1]
self.configuration.image_list.append(os.path.join("ATS3Drop", "images", image_name))
if self.configuration.sis_files:
for sis in self.configuration.sis_files:
tmp = string.rsplit(sis, os.sep)
sis_name = tmp[len(tmp)-1]
self.configuration.sis_list.append(dict(path=os.path.join("ATS3Drop", "sis", sis_name), dest=sis_name))
except KeyError, error:
_logger.error("Error in file reading / fetching!")
sys.stderr.write(error)
示例4: archiveimage
def archiveimage(imguri, localpostpath):
"save the image locally"
# read image data
imagedata = getcontentbinary(imguri)
# take the last part of the path after "/"
imagename = string.rsplit(imguri, "/", 1)[-1:][0]
# take the last part of the string after "."
extension = string.rsplit(imagename, ".", 1)[-1:][0]
# if the extension not in common format, what is it?
# TOFIX: corner cases
# foo.bar (but really foo.bar.png)
# foo (but really foo.png)
# foo.svg
if extension.lower() not in ["jpg", "png", "gif"]:
imagetype = imghdr.what(None, imagedata[:32])
if imagetype == "jpeg":
extension = "jpg"
else:
extension = imagetype
filename = "%s.%s" % (imagename, extension)
else:
filename = imagename
fullpath = "%s%s" % (localpostpath, filename)
# save the image
with open(fullpath, 'wb') as imagefile:
imagefile.write(imagedata)
logging.info("created image at %s" % (fullpath))
return filename
示例5: fetchData
def fetchData(command, prefix, lz = False):
if not power.is_on(): return
result = send_receive(command)
if not result : return
values = result.split('\r')
print values
for i in values:
idx = values.index(i)
# BGL: ['06/01/11', '30/06/04', '22749', '24069', '9857', '06/01/11 5', '04/04/10 1979']
if idx == 5 and command == "BGL":
splitted = string.rsplit(i, " ", 1)
data[prefix+str(6)]=splitted[0]
data[prefix+str(5)]=splitted[1]
elif idx == 6 and command == "BGL":
splitted = string.rsplit(i, " ", 1)
data[prefix+str(8)]=splitted[0]
data[prefix+str(7)]=splitted[1]
elif idx == 4 and lz:
splitted = string.rsplit(i, " ", 1)
data[prefix+str(5)]=splitted[0]
data[prefix+str(4)]=splitted[1]
elif idx == 5 and lz:
splitted = string.rsplit(i, " ", 1)
data[prefix+str(7)]=splitted[0]
data[prefix+str(6)]=splitted[1]
else:
data[prefix+str(idx)]=i
示例6: testMyDistro_restartSshService
def testMyDistro_restartSshService(self):
"""
Test MyDistro.restartSshService()
"""
cmd = 'service '+ waagent.MyDistro.ssh_service_name + ' status'
sshpid=string.rsplit(waagent.RunGetOutput(cmd)[1],' ',1)
waagent.MyDistro.restartSshService()
assert sshpid is not string.rsplit(waagent.RunGetOutput(cmd)[1],' ',1),'ssh server pid is unchanged.'
示例7: do_file
def do_file(fn, logs_dir=LOGS_DIR, dynamic_dates=False, timezone=None, logfn_keepdir=False):
if fn.endswith('.gz'):
fp = gzip.GzipFile(fn)
if logfn_keepdir:
fnb = fn.replace('/', '__')
else:
fnb = os.path.basename(fn)
if dynamic_dates:
ofn = string.rsplit(fnb, '.', 1)[0]
else:
ofn = string.rsplit(fnb, '.', 2)[0]
else:
fp = open(fn) # expect it ends with .log
ofn = string.rsplit(os.path.basename(fn), '.', 1)[0]
# if file has been done, then there will be a file denoting this in the META subdir
ofn = '%s/META/%s' % (logs_dir, ofn)
if os.path.exists(ofn):
print "Already done %s -> %s (skipping)" % (fn, ofn)
sys.stdout.flush()
return
print "Processing %s -> %s (%s)" % (fn, ofn, datetime.datetime.now())
sys.stdout.flush()
m = re.search('(\d\d\d\d-\d\d-\d\d)', fn)
if m:
the_date = m.group(1)
else:
the_date = None
cnt = 0
for line in fp:
cnt += 1
try:
newline = do_split(line, linecnt=cnt, run_rephrase=True, date=the_date, do_zip=True, logs_dir=logs_dir,
dynamic_dates=dynamic_dates, timezone=timezone)
except Exception as err:
print "[split_and_rephrase] ===> OOPS, failed err=%s in parsing line %s" % (str(err), line)
raise
if ((cnt % 10000)==0):
sys.stdout.write('.')
sys.stdout.flush()
print
mdir = '%s/META' % logs_dir
if not os.path.exists(mdir):
os.mkdir(mdir)
open(ofn, 'a').write(' ') # mark META
# close all file pointers
for fn, fp in ofpset.items():
fp.close()
ofpset.pop(fn)
print "...done (%s)" % datetime.datetime.now()
sys.stdout.flush()
示例8: fetch_kafka
def fetch_kafka():
print "Downloading ", DOWNLOAD_URL
exe('wget '+DOWNLOAD_URL)
print DOWNLOAD_URL
tgz=rsplit(DOWNLOAD_URL, "/", 1)[1]
print "Unpacking ", tgz
exe('tar -zxvf '+tgz)
global KAFKA_SRC
if KAFKA_SRC is None:
KAFKA_SRC = rsplit(tgz, ".tgz", 1)[0]
示例9: convert_comment
def convert_comment(comment):
#discard any comments without timestamp (for now)
if (comment[0] == None or comment[0] <= 0):
return ''
else:
#Convert created_at timestamp to unix timestamp, as required for gource
try:
timestamp = timegm(time.strptime(comment[0], "%Y/%m/%d %H:%M:%S +0000"))
except ValueError as ve:
print(comment[0]+' - value error - '+str(ve))
# maybe a different timezone
# if ('+' in comment[0] or '-' in comment[0]):
# if ('+' in comment[0]):
# split_time_and_timezone = string.rsplit(comment[0], '+', 1)
# multiplier = 1
# else:
# split_time_and_timezone = string.rsplit(comment[0], '-', 1)
# multiplier = -1
# split_time = time.strptime(split_time_and_timezone[0], "%Y/%m/%d %H:%M:%S ")
# timezone = int(int(split_time_and_timezone[1])/100) * multiplier
# split_time.tm_hour = split_time.tm_hour + timezone
# timestamp = timegm(split_time)
# but just ignore different timezone for now - life is too short! TODO
if ('+' in comment[0]):
split_time_and_timezone = string.rsplit(comment[0], '+', 1)
else:
if ('-' in comment[0]):
split_time_and_timezone = string.rsplit(comment[0], '-', 1)
else:
return ''
# multiplier = -1
timestamp = timegm(time.strptime(split_time_and_timezone[0], "%Y/%m/%d %H:%M:%S "))
except Exception as e:
print(comment[0]+' - exception - '+str(e))
return ''
# return str(int(timestamp))+'|'+str(comment[1])+'|'+str(comment[2])+'|'+str(comment[3])+'|'+str(hex(timestamp % 0xFFFFFF))[2:]+'\n'
# return_string timestamp | username | type | path of track, as user/trackid (to get best clusters of a user) | random_colour
# if (comment[2] == 'A'):
# return str(int(timestamp))+'|'+lower_case_str(comment[1])+'|'+comment[2]+'|'+comment[1]+'/'+str(comment[3])+'|'+str(hex(random.randint(0,0xFFFFCC)))[2:]+'\n'
# else:
return_string = str(int(timestamp))
return_string = return_string+'|'+lower_case_str(comment[1])
return_string = return_string+'|'+str(comment[2])
return_string = return_string+'|'+str(comment[4])
return_string = return_string+'/'+str(comment[3])
return_string = return_string+'|'+str(hex(random.randint(0,0xFFFFCC)))[2:]+'\n'
return return_string
示例10: updateFN
def updateFN(self):
#ext = item[-3:]
pr = self.projects_CB.currentText()
ep = self.episodes_CB.currentText()
sq = self.sequence_CB.currentText()
tk = self.task_CB.currentText()
nn = self.nn_LE.text()
self.ext = string.rsplit(cmds.file(q=True,sn=True),"/",1)[1].split(".")[-1]
if tk is not "data":
self.taskRootPath = self.seqRootPath + str(tk) + "/"
if nn == "":
self.sceneName = str(sq)+"_"+str(tk) + "." + self.ext
else:
if re.search("s[0-9][0-9][0-9][0-9]",nn):
self.sceneName = str(sq)+"_"+str(nn)+ "_"+str(tk)+"." + self.ext
else:
self.sceneName = str(sq)+"_"+str(tk)+"_"+str(nn) +"." + self.ext
self.fn_LE.setText(self.sceneName)
if str(tk) == "data":
if nn == "":
self.sceneName = str(sq) + "_" + "." + self.ext
else:
if re.search("s[0-9][0-9][0-9][0-9]",nn):
self.sceneName = str(sq)+"_"+str(nn)+ "." + self.ext
else:
self.sceneName = str(sq)+"_"+str(nn) + "." + self.ext
self.fn_LE.setText(self.sceneName)
示例11: xmlize_items
def xmlize_items(items, query):
items_a = []
for item in items:
list = string.rsplit(item, "/", 1)
name = list[-1]
path = item if len(list) == 2 else ""
complete = item
if item.lower().startswith(query.lower()):
i = item.find("/", len(query))
if i != -1:
complete = item[:(i+1)]
items_a.append("""
<item uid="%(item)s" arg="%(item)s" autocomplete="%(complete)s">
<title>%(name)s</title>
<subtitle>%(path)s</subtitle>
</item>
""" % {'item': item, 'name': name, 'path': path, 'complete': complete})
return """
<?xml version="1.0"?>
<items>
%s
</items>
""" % '\n'.join(items_a)
示例12: start_activity
def start_activity(self, cmp):
"""
Run the specified activity on the device
"""
fullCmpStr = string.rsplit(cmp, '.', 1)[0] + '/' + cmp
return self.shell_command('am start -a android.intent.action.MAIN -n %s' % (fullCmpStr))
示例13: _word_repl
def _word_repl(self, word, groups):
"""Handle WikiNames."""
bang_present = groups.get('word_bang')
if bang_present:
if self.cfg.bang_meta:
return self.formatter.nowikiword("!%s" % word)
else:
self.formatter.text('!')
name = groups.get('word_name')
current_page = self.formatter.page.page_name
abs_name = wikiutil.AbsPageName(current_page, name)
if abs_name == current_page:
self.currentitems.append(('wikilink', (abs_name, abs_name)))
self.__add_meta(abs_name, groups)
return u''
else:
# handle anchors
try:
abs_name, anchor = rsplit(abs_name, "#", 1)
except ValueError:
anchor = ""
if self.cat_re.match(abs_name):
self.currentitems.append(('category', (abs_name)))
self.__add_meta(abs_name, groups)
else:
if not anchor:
wholename = abs_name
else:
wholename = "%s#%s" % (abs_name, anchor)
self.currentitems.append(('wikilink', (wholename, abs_name)))
self.__add_meta(wholename, groups)
return u''
示例14: MagnetSetHeater
def MagnetSetHeater(self, State):
HeaterBefore = self.MagnetReadHeater()
if State == 1:
Reply = self.Visa.ask("SET:DEV:GRPZ:PSU:SIG:SWHT:ON")
elif State == 0:
Reply = self.Visa.ask("SET:DEV:GRPZ:PSU:SIG:SWHT:OFF")
else:
print "Error cannot set switch heater\n"
Answer = string.rsplit(Reply,":",1)[1]
if Answer == "VALID":
Heater = 1
elif Answer == "INVALID":
Heater = 0
else:
Heater = -1
HeaterAfter = self.MagnetReadHeater()
if HeaterAfter != HeaterBefore:
print "Heater Switched! Waiting 4 min\n"
time.sleep(240)
print "Finished wait!\n"
return Heater
示例15: importPlanner
def importPlanner(module_or_file_name=None):
if module_or_file_name is None:
if len(argv) != 2:
print "Usage: %s <planner-module>" % argv[0]
exit(2)
module_or_file_name = argv[1].strip()
if module_or_file_name.endswith(".py"):
module_or_file_name = module_or_file_name[:-3]
try:
dirname, filename = string.rsplit(module_or_file_name, '/', 1)
path.append(dirname)
except ValueError:
filename = module_or_file_name
module = __import__(filename)
try:
if hasattr(module, 'controller'):
if hasattr(module, 'graceful_exit'):
return module.update, module.controller, module.graceful_exit
return module.update, module.controller
else:
return module.update
except AttributeError:
raise AttributeError("The planner module must have an update() function.")