本文整理汇总了Python中mx.Tools类的典型用法代码示例。如果您正苦于以下问题:Python Tools类的具体用法?Python Tools怎么用?Python Tools使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Tools类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clear_cache
def clear_cache(self):
""" Clears the caches used (flushing any data not yet
written).
"""
if self.caching:
#self.flush()
Tools.method_mapply(self.caches,'clear',())
示例2: rpcdecode
def rpcdecode(url,prefix='',decode=1,
splitat=TextTools.splitat,charsplit=TextTools.charsplit,
len=len,tuple=tuple,urldecode=urldecode):
""" Decode a RPC encoded function/method call.
Returns a tuple (name,args,kws) where args is a tuple of
string arguments and kws is a dictionary containing the given
keyword parameters or None. All parameters are returned as
strings; it is up to the caller to decode them into
e.g. integers, etc.
If prefix is given and found it is removed from the name prior
to returning it. decode can be set to false to prevent the url
from being urldecoded prior to processing.
The decode function also supports the syntax 'method' instead
of 'method()' for calls without arguments.
"""
if decode:
url = urldecode(url)
# Decode the method: method[(arg0,arg1,...,kw0=val0,kw1=val1,...)]
name,rawargs = splitat(url,'(')
if rawargs:
# Cut out the pure argument part, ignoring any character after
# the final ')'
rawargs,rest = splitat(rawargs,')',-1)
# Argument list: split at ','
args = charsplit(rawargs,',')
if '=' in rawargs:
kws = {}
for i,arg in Tools.reverse(Tools.irange(args)):
if '=' in arg:
k,v = splitat(arg,'=')
kws[k] = v
del args[i]
else:
kws = None
args = tuple(args)
else:
args = ()
kws = None
if prefix:
if name[:len(prefix)] == prefix:
name = name[len(prefix):]
return name,args,kws
else:
return name,args,kws
示例3: feed_list
def feed_list(self,table):
""" Feeds a table (list of rows) which is converted
to CSV.
No more than len(columns) items are written for each
row. All rows are filled up with "" entries to have an
equal number of items. None entries are converted to empty
strings, all other objects are stringified.
"""
columns = self.columns
if columns:
rowlen = len(columns)
else:
# Calculate the max. number of columns in the table
rowlen = max(map(len,table))
# Prepare an empty table
t = [None] * len(table)
_quote = self._quote
# Fill in data
for i,row in Tools.irange(table):
row = _quote(row[:rowlen])
if len(row) < rowlen:
row[len(row):] = ['""'] * (rowlen - len(row))
t[i] = self.separator.join(row)
# Add final CRLF and add as CSV text
t.append('')
self.text = self.text + self.lineend.join(t)
示例4: print_stack
def print_stack(file=_sys.stdout,levels=100,offset=0,locals=0):
# Prepare frames
try:
raise ValueError
except ValueError:
# Go back offset+1 frames...
f = _sys.exc_info()[2].tb_frame
for i in range(offset + 1):
if f.f_back is not None:
f = f.f_back
# Extract frames
frames = []
while f:
frames.append(f)
f = f.f_back
frames.reverse()
# Prepare stack
stack = _traceback.extract_stack()
# Make output
file.write('Stack:\n')
for (frame,(filename, lineno, name, line)) in \
Tools.tuples(frames,stack)[-levels:]:
file.write(' File "%s", line %d, in %s\n' % (filename,lineno,name))
if line:
file.write(' %s\n' % line.strip())
if locals:
print_frame_locals(frame,file,indent=' |',title='')
示例5: print_recursive
def print_recursive(obj,file=_sys.stdout,indent='',levels=1,
nonrecursive=(),filter=None):
# Filter out nonrecursive types and objects
try:
if type(obj) in nonrecursive or \
obj in nonrecursive:
return
except:
# Error during compares result in the object not being
# printed
return
# Print the object depending on its interface
if hasattr(obj,'__dict__') and \
obj.__dict__ is not None:
print_dict(obj.__dict__,file,indent,levels,
nonrecursive=nonrecursive, filter=filter)
elif hasattr(obj,'items'):
print_dict(obj,file,indent,levels,1,
nonrecursive=nonrecursive, filter=filter)
elif Tools.issequence(obj) and not is_string(obj):
print_sequence(obj,file,indent,levels,
nonrecursive=nonrecursive)
elif hasattr(obj,'__members__'):
d = {}
for attr in obj.__members__:
d[attr] = getattr(obj,attr)
print_dict(d, file, indent, levels,
nonrecursive=nonrecursive, filter=filter)
示例6: search_bench
def search_bench(word, text):
iterations = Tools.trange(COUNT)
print ('Searching for all occurences of %r using ...' % word)
t0 = time.time()
so = TextTools.TextSearch(word)
for i in iterations:
l = so.findall(text)
t1 = time.time()
count = len(l)
print (' - mx.TextSearch.TextSearch().findall(): %5.3f ms (%i)' %
((t1 - t0) / COUNT * 1000.0, count))
t0 = time.time()
so = re.compile(word)
for i in iterations:
l = so.findall(text)
t1 = time.time()
count = len(l)
print (' - re.compile().findall(): %5.3f ms (%i)' %
((t1 - t0) / COUNT * 1000.0, count))
t0 = time.time()
for i in iterations:
count = text.count(word)
t1 = time.time()
print (' - text.count(): %5.3f ms (%i)' %
((t1 - t0) / COUNT * 1000.0, count))
示例7: free
def free(self,position,
OLD=OLD,HOT=HOT):
""" Deletes an already written record by marking it OLD.
The next garbage collection will make the change permanent
and free the occupied space.
"""
if self.state != HOT:
self.mark(HOT)
file = self.file
file.seek(position + 5)
file.write(OLD)
if self.caching:
Tools.method_mapply(self.caches,'delete',(position,))
示例8: objects
def objects(self,constructor):
""" Builds a list of objects by calling the given constructor
with keywords defined by mapping column names to values for
each input line.
.columns must have been set using .set_columns() or by
processing a given CSV header.
"""
lines = self.lines
keys = self.columns
if keys is None:
raise Error,'no columns set'
objs = [None] * len(lines)
for i,line in Tools.irange(lines):
kws = dict(Tools.tuples(keys, line))
objs[i] = apply(constructor,(),kws)
return objs
示例9: feed_dict
def feed_dict(self,table,rows=None):
""" Feeds a table (dict of lists) which is converted
to CSV.
Only the keys set as column names are used to form the CSV
data.
All lists in the dictionary must have equal length or at
least rows number of entries, if rows is given. None
entries are converted to empty strings, all other objects
are stringified.
"""
columns = self.columns
if not columns:
raise Error,'no output columns set'
rowlen = len(columns)
# Create an emtpy table
if not rows:
rows = 0
for column in columns:
nrows = len(table[column])
if nrows > rows:
rows = nrows
rowindices = Tools.trange(rows)
t = [None] * rows
for i in rowindices:
t[i] = [None] * rowlen
# Fill the table
for j,k in Tools.irange(columns):
for i in rowindices:
t[i][j] = table[k][i]
# Quote and join lines
t = [self.separator.join(self._quote(x)) for x in t]
# Add final CRLF and store CSV text
t.append('')
self.text = self.text + self.lineend.join(t)
示例10: _unquote
def _unquote(self,line):
""" Unquote a CSV style quoted line of text.
Internal method. Do not use directly.
"""
for i,text in Tools.irange(line):
if text[:1] == '"' and text[-1:] == '"':
text = text[1:-1]
line[i] = text.replace('""','"')
return line
示例11: feed_objects
def feed_objects(self,objects,
getattr=getattr):
""" Feeds a sequence of objects which is converted to CSV.
For each object the set column names are interpreted as
object attributes and used as basis for the CSV data.
None values are converted to empty strings, all other
attributes are added stringified.
"""
columns = self.columns
if not columns:
raise Error,'no output columns set'
rowlen = len(columns)
# Create an emtpy table
rows = len(objects)
rowindices = Tools.trange(rows)
t = [None] * rows
for i in rowindices:
t[i] = [None] * rowlen
# Fill the table
icols = Tools.irange(columns)
for i in rowindices:
obj = objects[i]
for j,name in icols:
t[i][j] = str(getattr(obj, name))
# Quote and join lines
t = [self.separator.join(self._quote(x)) for x in t]
# Add final CRLF and store CSV text
t.append('')
self.text = self.text + self.lineend.join(t)
示例12: dictionary
def dictionary(self):
""" Return the current data as dictionary of lists of strings,
with one entry for each column.
.columns must have been set using .set_columns() or by
processing a given CSV header.
"""
table = {}
lines = self.lines
keys = self.columns
if keys is None:
raise Error,'no columns set'
rows = len(lines)
for k in keys:
table[k] = [None] * rows
for i, key in Tools.irange(keys):
column = table[key]
for j, row in Tools.irange(lines):
if len(row) > i:
column[j] = row[i]
return table
示例13: _quote
def _quote(self, line,
str=str):
""" CSV style quote the given line of text.
"""
nline = ['""'] * len(line)
for i,item in Tools.irange(line):
if item is not None:
text = str(item)
else:
text = ''
nline[i] = '"%s"' % text.replace('"','""')
return nline
示例14: _quote
def _quote(self, line,
str=str):
""" CSV style quote the given line of text.
"""
nline = ['""'] * len(line)
for i,item in Tools.irange(line):
if item is None:
text = ''
elif isinstance(item, unicode):
text = item.encode(self.encoding)
else:
text = str(item)
nline[i] = '"%s"' % text.replace('"','""')
return nline
示例15: filter_header
def filter_header(self, header,
lower=TextTools.lower):
""" Filter the given header line.
The base class converts the column names to all lowercase
and removes any whitespace included in the header.
This method is only called in case the header was read
from the data provided to the object.
"""
l = [''] * len(header)
for i,column in Tools.irange(header):
l[i] = ''.join(lower(column).split())
return l