def printexpr(expr_string):
""" printexpr(expr) -
print the value of the expression, along with linenumber and filename.
"""
stack = extract_stack ( )[-2:][0]
actualCall = stack[3]
left = string.find ( actualCall, '(' )
right = string.rfind ( actualCall, ')' )
caller_globals,caller_locals = _caller_symbols()
expr = eval(expr_string,caller_globals,caller_locals)
varType = type( expr )
stderr.write("%s:%d> %s == %s (%s)\n" % (
stack[0], stack[1],
string.strip( actualCall[left+1:right] )[1:-1],
repr(expr), str(varType)[7:-2]))
python类rfind()的实例源码
def lineReceived(self, line):
parts = string.split(line)
if not parts:
parts = ['']
if len(parts) == 1:
slash_w = 0
else:
slash_w = 1
user = parts[-1]
if '@' in user:
host_place = string.rfind(user, '@')
user = user[:host_place]
host = user[host_place+1:]
return self.forwardQuery(slash_w, user, host)
if user:
return self.getUser(slash_w, user)
else:
return self.getDomain(slash_w)
def write(self, out_filename):
"""Create the FFFF file
Create the FFFF file, write the FFFF ROMimage buffer to it and return
a success flag. Appends the default FFFF file extension if omitted
"""
# Reject the write if we didn't pass the sniff test
if self.ffff0.header_validity != FFFF_HDR_VALID:
raise ValueError("Invalid FFFF header 0")
if self.ffff1.header_validity != FFFF_HDR_VALID:
raise ValueError("Invalid FFFF header 1")
# Ensure the output file ends in the default file extension if
# the user hasn't specified their own extension.
if rfind(out_filename, ".") == -1:
out_filename += FFFF_FILE_EXTENSION
# Output the entire FFFF blob
with open(out_filename, 'wb') as wf:
wf.write(self.ffff_buf)
print("Wrote", out_filename)
return True
def lineReceived(self, line):
parts = string.split(line)
if not parts:
parts = ['']
if len(parts) == 1:
slash_w = 0
else:
slash_w = 1
user = parts[-1]
if '@' in user:
host_place = string.rfind(user, '@')
user = user[:host_place]
host = user[host_place+1:]
return self.forwardQuery(slash_w, user, host)
if user:
return self.getUser(slash_w, user)
else:
return self.getDomain(slash_w)
def get_searches(self):
elements = re.split('<tr>', self.page)
for index in range(1, len(elements), 1):
element = elements[index]
titleandid = gutils.trim(element, '<td class="title">', '</td>')
title = gutils.clean(titleandid)
id = gutils.trim(titleandid, 'href="', '"')
idstart = string.rfind(id, '/')
id = id[idstart + 1:]
year = gutils.trim(element, '<td class="year">', '</td>')
self.ids.append(id)
self.titles.append(title + ' (' + gutils.clean(year)+ ')')
#
# Plugin Test
#
def _fixupParents(self, alogger):
"""
Ensure that there are either loggers or placeholders all the way
from the specified logger to the root of the logger hierarchy.
"""
name = alogger.name
i = string.rfind(name, ".")
rv = None
while (i > 0) and not rv:
substr = name[:i]
if not self.loggerDict.has_key(substr):
self.loggerDict[substr] = PlaceHolder(alogger)
else:
obj = self.loggerDict[substr]
if isinstance(obj, Logger):
rv = obj
else:
assert isinstance(obj, PlaceHolder)
obj.append(alogger)
i = string.rfind(name, ".", 0, i - 1)
if not rv:
rv = self.root
alogger.parent = rv
def mput(outarray,fname,writeheader=0,btype=N.int16):
"""
Save a file for use in matlab.
"""
outarray = N.transpose(outarray)
outdata = N.ravel(outarray).astype(btype)
outdata = outdata.tostring()
outfile = open(fname,'wb')
outfile.write(outdata)
outfile.close()
if writeheader == 1:
try:
suffixindex = string.rfind(fname,'.')
hdrname = fname[0:suffixindex]
except ValueError:
hdrname = fname
if len(outarray.shape) == 2:
hdr = [outarray.shape[1],outarray.shape[0], 1, 0]
else:
hdr = [outarray.shape[2],outarray.shape[1],outarray.shape[0], 0,'\n']
print hdrname+'.hdr'
outfile = open(hdrname+'.hdr','w')
outfile.write(pstat.list2string(hdr))
outfile.close()
return None
def getCurrentWord(self, entry):
i = entry.get_point()
text = entry.get_chars(0,-1)
word = re.split(r'\s', text)[-1]
start = string.rfind(text, word)
end = start+len(word)
return (word, (start, end))
def isCursorOnLastLine(entry):
if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'):
return 1
def get_leafname(self, path):
"""Get the leafname of the specified file."""
pos = string.rfind(path, os.sep)
if pos != -1:
return path[pos+1:]
else:
return path
def convert(label):
if not label.startswith("//"):
sys.stderr.write("expected label to start with //, got %s\n" % label)
return 1
base = _remove_sdk_dir(label[2:])
separator_index = string.rfind(base, ":")
if separator_index < 0:
sys.stderr.write("could not find target name in label %s\n" % label)
return 1
path = base[:separator_index].split("/")
name = base[separator_index+1:]
if path[-1] == name:
return ".".join(path)
else:
return "%s._%s" % (".".join(path), name)
def get_target(label):
if not label.startswith("//"):
raise Exception("Expected label to start with //, got %s" % label)
base = label[2:]
separator_index = string.rfind(base, ":")
if separator_index >= 0:
name = base[separator_index+1:]
path = base[:separator_index]
else:
name = base[base.rfind("/")+1:]
path = base
return path, name
# Updates paths in a TOML block.
def split(p):
"""
Split a path in head (everything up to the last '.') and tail (the rest). FS
name must still be dealt with separately since special field may contain '.'.
"""
(fs, drive, path)= _split(p)
q= string.rfind(path, '.')
if q!=-1:
return (fs+drive+path[:q], path[q+1:])
return ('', p)
def splitext(p):
"""
Split a path in root and extension. This assumes the 'using slash for dot and
dot for slash with foreign files' convention common in RISC OS is in force.
"""
(tail, head)= split(p)
if '/' in head:
q= len(head)-string.rfind(head, '/')
return (p[:-q], p[-q:])
return (p, '')
def split(p):
"""
Split a path in head (everything up to the last '.') and tail (the rest). FS
name must still be dealt with separately since special field may contain '.'.
"""
(fs, drive, path)= _split(p)
q= string.rfind(path, '.')
if q!=-1:
return (fs+drive+path[:q], path[q+1:])
return ('', p)
def splitext(p):
"""
Split a path in root and extension. This assumes the 'using slash for dot and
dot for slash with foreign files' convention common in RISC OS is in force.
"""
(tail, head)= split(p)
if '/' in head:
q= len(head)-string.rfind(head, '/')
return (p[:-q], p[-q:])
return (p, '')
def get_leafname(path):
"""Get the leafname of the specified file."""
pos = string.rfind(path, os.sep)
if pos != -1:
return path[pos+1:]
else:
return path
def write(self, out_filename):
"""Create the TFTF file and return a success flag
Create the TFTF file (appending the default extension if omitted)
and write the TFTF buffer to it.
"""
success = True
# Prepare the output buffer
self.pack()
# Record the length of the entire TFTF blob (this will be longer
# than the header's load_length)
self.tftf_length = len(self.tftf_buf)
# Ensure the output file ends in the default TFTF file extension if
# the user hasn't specified their own extension.
if rfind(out_filename, ".") == -1:
out_filename += TFTF_FILE_EXTENSION
try:
with open(out_filename, 'wb') as wf:
# Write the TFTF header
wf.write(self.tftf_buf)
# verify the file is the correct length
try:
statinfo = os.stat(out_filename)
if statinfo.st_size != self.tftf_length:
error(out_filename, "has wrong length")
except:
error("Can't get info on", out_filename)
except:
error("Unable to write", out_filename)
success = False
else:
if success:
print("Wrote", out_filename)
else:
error("Failed to write", out_filename)
return success
def getCurrentWord(self, entry):
i = entry.get_point()
text = entry.get_chars(0,-1)
word = re.split(r'\s', text)[-1]
start = string.rfind(text, word)
end = start+len(word)
return (word, (start, end))
def isCursorOnLastLine(entry):
if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'):
return 1
def __get_background_url(self, url):
# background-image: url('http://img.178.com/dota2/201511/241827471049/241827723987.jpg');
start_index = string.find(url, "'")
end_index = string.rfind(url, "'")
return url[start_index + 1:end_index]
def split(p):
"""
Split a path in head (everything up to the last '.') and tail (the rest). FS
name must still be dealt with separately since special field may contain '.'.
"""
(fs, drive, path)= _split(p)
q= string.rfind(path, '.')
if q!=-1:
return (fs+drive+path[:q], path[q+1:])
return ('', p)
def splitext(p):
"""
Split a path in root and extension. This assumes the 'using slash for dot and
dot for slash with foreign files' convention common in RISC OS is in force.
"""
(tail, head)= split(p)
if '/' in head:
q= len(head)-string.rfind(head, '/')
return (p[:-q], p[-q:])
return (p, '')
def rtrim(text, key1, key2):
p1 = string.rfind(text, key2)
if p1 == -1:
return ''
p2 = string.rfind(text[:p1], key1)
if p2 == -1:
return ""
else:
p2 = p2 + len(key1)
return text[p2:p1]
def get_trailer(self):
# Find the film's trailer page or location
self.trailer = ''
pos_end = string.find(self.page, '>guarda il trailer<')
if pos_end > -1:
pos_beg = string.rfind(self.page[:pos_end], '<a href')
if pos_beg > -1:
self.trailer = gutils.trim(self.page[pos_beg:pos_end], '"', '"')
def get_o_site(self):
self.o_site = ""
try:
index = string.rfind(self.page, u'title="oficiální web"')
if index > 0:
tmp = gutils.before(self.page, u'title="oficiální web"')
index = string.rfind(tmp, 'href="')
if index > 0:
self.o_site = gutils.trim(tmp[index:], '"', '"')
except:
pass
def get_nextpage_url(self):
match = re.search('(siguientes >|siguientes >)', self.page)
if match:
start = string.rfind(self.page, '<a href="', 0, match.start())
if start >= 0:
return 'http://www.filmaffinity.com/es/' + gutils.before(self.page[start + 9:match.start()], '"')
return None
def get_trailer(self):
self.trailer = ''
tmp = string.find(self.page, u'(trailers)')
if tmp >= 0:
index = string.rfind(self.page[:tmp], u'<a href="')
if index >= 0:
self.trailer = gutils.before(self.page[index + 9:], '"')
def rename(source, dest):
"""
Renames files specified by UNIX inpattern to those specified by UNIX
outpattern. Can only handle a single '*' in the two patterns!!!
Usage: rename (source, dest) e.g., rename('*.txt', '*.c')
"""
infiles = glob.glob(source)
outfiles = []
incutindex = string.index(source,'*')
outcutindex = string.index(source,'*')
findpattern1 = source[0:incutindex]
findpattern2 = source[incutindex+1:]
replpattern1 = dest[0:incutindex]
replpattern2 = dest[incutindex+1:]
for fname in infiles:
if incutindex > 0:
newname = re.sub(findpattern1,replpattern1,fname,1)
if outcutindex < len(dest)-1:
if incutindex > 0:
lastone = string.rfind(newname,replpattern2)
newname = newname[0:lastone] + re.sub(findpattern2,replpattern2,fname[lastone:],1)
else:
lastone = string.rfind(fname,findpattern2)
if lastone <> -1:
newname = fname[0:lastone]
newname = newname + re.sub(findpattern2,replpattern2,fname[lastone:],1)
os.rename(fname,newname)
return
def bput(outarray,fname,writeheader=0,packtype=N.int16,writetype='wb'):
"""
Writes the passed array to a binary output file, and then closes
the file. Default is overwrite the destination file.
Usage: bput (outarray,filename,writeheader=0,packtype=N.int16,writetype='wb')
"""
suffix = fname[-6:]
if suffix == 'bshort':
packtype = N.int16
elif suffix == 'bfloat':
packtype = N.Float32
else:
print 'Not a bshort or bfloat file. Using packtype=',packtype
outdata = N.ravel(outarray).astype(packtype)
littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) )
if littleEndian and os.uname()[0]<>'Linux':
outdata = outdata.byteswapped()
outdata = outdata.tostring()
outfile = open(fname,writetype)
outfile.write(outdata)
outfile.close()
if writeheader == 1:
try:
suffixindex = string.rfind(fname,'.')
hdrname = fname[0:suffixindex]
except ValueError:
hdrname = fname
if len(outarray.shape) == 2:
hdr = [outarray.shape[0],outarray.shape[1], 1, 0]
else:
hdr = [outarray.shape[1],outarray.shape[2],outarray.shape[0], 0,'\n']
print hdrname+'.hdr'
outfile = open(hdrname+'.hdr','w')
outfile.write(pstat.list2string(hdr))
outfile.close()
return None