INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Format the exception part of a traceback.
def _format_exception_only(self, etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.exc_info()[:2]. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. Also lifted nearly verbatim from traceback.py """ have_filedata = False Colors = self.Colors list = [] stype = Colors.excName + etype.__name__ + Colors.Normal if value is None: # Not sure if this can still happen in Python 2.6 and above list.append( str(stype) + '\n') else: if etype is SyntaxError: have_filedata = True #print 'filename is',filename # dbg if not value.filename: value.filename = "<string>" list.append('%s File %s"%s"%s, line %s%d%s\n' % \ (Colors.normalEm, Colors.filenameEm, value.filename, Colors.normalEm, Colors.linenoEm, value.lineno, Colors.Normal )) if value.text is not None: i = 0 while i < len(value.text) and value.text[i].isspace(): i += 1 list.append('%s %s%s\n' % (Colors.line, value.text.strip(), Colors.Normal)) if value.offset is not None: s = ' ' for c in value.text[i:value.offset-1]: if c.isspace(): s += c else: s += ' ' list.append('%s%s^%s\n' % (Colors.caret, s, Colors.Normal) ) try: s = value.msg except Exception: s = self._some_str(value) if s: list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, Colors.Normal, s)) else: list.append('%s\n' % str(stype)) # sync with user hooks if have_filedata: ipinst = ipapi.get() if ipinst is not None: ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) return list
Only print the exception type and message without a traceback.
def show_exception_only(self, etype, evalue): """Only print the exception type and message, without a traceback. Parameters ---------- etype : exception type value : exception value """ # This method needs to use __call__ from *this* class, not the one from # a subclass whose signature or behavior may be different ostream = self.ostream ostream.flush() ostream.write('\n'.join(self.get_exception_only(etype, evalue))) ostream.flush()
Return a nice text document describing the traceback.
def structured_traceback(self, etype, evalue, etb, tb_offset=None, context=5): """Return a nice text document describing the traceback.""" tb_offset = self.tb_offset if tb_offset is None else tb_offset # some locals try: etype = etype.__name__ except AttributeError: pass Colors = self.Colors # just a shorthand + quicker name lookup ColorsNormal = Colors.Normal # used a lot col_scheme = self.color_scheme_table.active_scheme_name indent = ' '*INDENT_SIZE em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) undefined = '%sundefined%s' % (Colors.em, ColorsNormal) exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) # some internal-use functions def text_repr(value): """Hopefully pretty robust repr equivalent.""" # this is pretty horrible but should always return *something* try: return pydoc.text.repr(value) except KeyboardInterrupt: raise except: try: return repr(value) except KeyboardInterrupt: raise except: try: # all still in an except block so we catch # getattr raising name = getattr(value, '__name__', None) if name: # ick, recursion return text_repr(name) klass = getattr(value, '__class__', None) if klass: return '%s instance' % text_repr(klass) except KeyboardInterrupt: raise except: return 'UNRECOVERABLE REPR FAILURE' def eqrepr(value, repr=text_repr): return '=%s' % repr(value) def nullrepr(value, repr=text_repr): return '' # meat of the code begins try: etype = etype.__name__ except AttributeError: pass if self.long_header: # Header with the exception type, python version, and date pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, exc, ' '*(75-len(str(etype))-len(pyver)), pyver, date.rjust(75) ) head += "\nA problem occured executing Python code. Here is the sequence of function"\ "\ncalls leading up to the error, with the most recent (innermost) call last." else: # Simplified header head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, 'Traceback (most recent call last)'.\ rjust(75 - len(str(etype)) ) ) frames = [] # Flush cache before calling inspect. This helps alleviate some of the # problems with python 2.3's inspect.py. ##self.check_cache() # Drop topmost frames if requested try: # Try the default getinnerframes and Alex's: Alex's fixes some # problems, but it generates empty tracebacks for console errors # (5 blanks lines) where none should be returned. #records = inspect.getinnerframes(etb, context)[tb_offset:] #print 'python records:', records # dbg records = _fixed_getinnerframes(etb, context, tb_offset) #print 'alex records:', records # dbg except: # FIXME: I've been getting many crash reports from python 2.3 # users, traceable to inspect.py. If I can find a small test-case # to reproduce this, I should either write a better workaround or # file a bug report against inspect (if that's the real problem). # So far, I haven't been able to find an isolated example to # reproduce the problem. inspect_error() traceback.print_exc(file=self.ostream) info('\nUnfortunately, your original traceback can not be constructed.\n') return '' # build some color string templates outside these nested loops tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ (Colors.vName, Colors.valEm, ColorsNormal) tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, Colors.vName, ColorsNormal) tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, ColorsNormal) # now, loop over all records printing context and info abspath = os.path.abspath for frame, file, lnum, func, lines, index in records: #print '*** record:',file,lnum,func,lines,index # dbg if not file: file = '?' elif not(file.startswith("<") and file.endswith(">")): # Guess that filenames like <string> aren't real filenames, so # don't call abspath on them. try: file = abspath(file) except OSError: # Not sure if this can still happen: abspath now works with # file names like <string> pass link = tpl_link % file args, varargs, varkw, locals = inspect.getargvalues(frame) if func == '?': call = '' else: # Decide whether to include variable details or not var_repr = self.include_vars and eqrepr or nullrepr try: call = tpl_call % (func,inspect.formatargvalues(args, varargs, varkw, locals,formatvalue=var_repr)) except KeyError: # This happens in situations like errors inside generator # expressions, where local variables are listed in the # line, but can't be extracted from the frame. I'm not # 100% sure this isn't actually a bug in inspect itself, # but since there's no info for us to compute with, the # best we can do is report the failure and move on. Here # we must *not* call any traceback construction again, # because that would mess up use of %debug later on. So we # simply report the failure and move on. The only # limitation will be that this frame won't have locals # listed in the call signature. Quite subtle problem... # I can't think of a good way to validate this in a unit # test, but running a script consisting of: # dict( (k,v.strip()) for (k,v) in range(10) ) # will illustrate the error, if this exception catch is # disabled. call = tpl_call_fail % func # Don't attempt to tokenize binary files. if file.endswith(('.so', '.pyd', '.dll')): frames.append('%s %s\n' % (link,call)) continue elif file.endswith(('.pyc','.pyo')): # Look up the corresponding source file. file = pyfile.source_from_cache(file) def linereader(file=file, lnum=[lnum], getline=linecache.getline): line = getline(file, lnum[0]) lnum[0] += 1 return line # Build the list of names on this line of code where the exception # occurred. try: names = [] name_cont = False for token_type, token, start, end, line in generate_tokens(linereader): # build composite names if token_type == tokenize.NAME and token not in keyword.kwlist: if name_cont: # Continuation of a dotted name try: names[-1].append(token) except IndexError: names.append([token]) name_cont = False else: # Regular new names. We append everything, the caller # will be responsible for pruning the list later. It's # very tricky to try to prune as we go, b/c composite # names can fool us. The pruning at the end is easy # to do (or the caller can print a list with repeated # names if so desired. names.append([token]) elif token == '.': name_cont = True elif token_type == tokenize.NEWLINE: break except (IndexError, UnicodeDecodeError): # signals exit of tokenizer pass except tokenize.TokenError,msg: _m = ("An unexpected error occurred while tokenizing input\n" "The following traceback may be corrupted or invalid\n" "The error message is: %s\n" % msg) error(_m) # Join composite names (e.g. "dict.fromkeys") names = ['.'.join(n) for n in names] # prune names list of duplicates, but keep the right order unique_names = uniq_stable(names) # Start loop over vars lvals = [] if self.include_vars: for name_full in unique_names: name_base = name_full.split('.',1)[0] if name_base in frame.f_code.co_varnames: if locals.has_key(name_base): try: value = repr(eval(name_full,locals)) except: value = undefined else: value = undefined name = tpl_local_var % name_full else: if frame.f_globals.has_key(name_base): try: value = repr(eval(name_full,frame.f_globals)) except: value = undefined else: value = undefined name = tpl_global_var % name_full lvals.append(tpl_name_val % (name,value)) if lvals: lvals = '%s%s' % (indent,em_normal.join(lvals)) else: lvals = '' level = '%s %s\n' % (link,call) if index is None: frames.append(level) else: frames.append('%s%s' % (level,''.join( _format_traceback_lines(lnum,index,lines,Colors,lvals, col_scheme)))) # Get (safely) a string form of the exception info try: etype_str,evalue_str = map(str,(etype,evalue)) except: # User exception is improperly defined. etype,evalue = str,sys.exc_info()[:2] etype_str,evalue_str = map(str,(etype,evalue)) # ... and format it exception = ['%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str)] if (not py3compat.PY3) and type(evalue) is types.InstanceType: try: names = [w for w in dir(evalue) if isinstance(w, basestring)] except: # Every now and then, an object with funny inernals blows up # when dir() is called on it. We do the best we can to report # the problem and continue _m = '%sException reporting error (object with broken dir())%s:' exception.append(_m % (Colors.excName,ColorsNormal)) etype_str,evalue_str = map(str,sys.exc_info()[:2]) exception.append('%s%s%s: %s' % (Colors.excName,etype_str, ColorsNormal, evalue_str)) names = [] for name in names: value = text_repr(getattr(evalue, name)) exception.append('\n%s%s = %s' % (indent, name, value)) # vds: >> if records: filepath, lnum = records[-1][1:3] #print "file:", str(file), "linenb", str(lnum) # dbg filepath = os.path.abspath(filepath) ipinst = ipapi.get() if ipinst is not None: ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) # vds: << # return all our info assembled as a single string # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) return [head] + frames + [''.join(exception[0])]
Call up the pdb debugger if desired always clean up the tb reference.
def debugger(self,force=False): """Call up the pdb debugger if desired, always clean up the tb reference. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. If the call_pdb flag is set, the pdb interactive debugger is invoked. In all cases, the self.tb reference to the current traceback is deleted to prevent lingering references which hamper memory management. Note that each call to pdb() does an 'import readline', so if your app requires a special setup for the readline completers, you'll have to fix that by hand after invoking the exception handler.""" if force or self.call_pdb: if self.pdb is None: self.pdb = debugger.Pdb( self.color_scheme_table.active_scheme_name) # the system displayhook may have changed, restore the original # for pdb display_trap = DisplayTrap(hook=sys.__displayhook__) with display_trap: self.pdb.reset() # Find the right frame so we don't pop up inside ipython itself if hasattr(self,'tb') and self.tb is not None: etb = self.tb else: etb = self.tb = sys.last_traceback while self.tb is not None and self.tb.tb_next is not None: self.tb = self.tb.tb_next if etb and etb.tb_next: etb = etb.tb_next self.pdb.botframe = etb.tb_frame self.pdb.interaction(self.tb.tb_frame, self.tb) if hasattr(self,'tb'): del self.tb
Switch to the desired mode.
def set_mode(self,mode=None): """Switch to the desired mode. If mode is not specified, cycles through the available modes.""" if not mode: new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ len(self.valid_modes) self.mode = self.valid_modes[new_idx] elif mode not in self.valid_modes: raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ 'Valid modes: '+str(self.valid_modes) else: self.mode = mode # include variable details only in 'Verbose' mode self.include_vars = (self.mode == self.valid_modes[2]) # Set the join character for generating text tracebacks self.tb_join_char = self._join_chars[self.mode]
View decorator for requiring a user group.
def group_required(group, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, skip_superuser=True): """ View decorator for requiring a user group. """ def decorator(view_func): @login_required(redirect_field_name=redirect_field_name, login_url=login_url) def _wrapped_view(request, *args, **kwargs): if not (request.user.is_superuser and skip_superuser): if request.user.groups.filter(name=group).count() == 0: raise PermissionDenied return view_func(request, *args, **kwargs) return _wrapped_view return decorator
parent name = get_parent ( globals level )
def get_parent(globals, level): """ parent, name = get_parent(globals, level) Return the package that an import is being performed in. If globals comes from the module foo.bar.bat (not itself a package), this returns the sys.modules entry for foo.bar. If globals is from a package's __init__.py, the package's entry in sys.modules is returned. If globals doesn't come from a package or a module in a package, or a corresponding entry is not found in sys.modules, None is returned. """ orig_level = level if not level or not isinstance(globals, dict): return None, '' pkgname = globals.get('__package__', None) if pkgname is not None: # __package__ is set, so use it if not hasattr(pkgname, 'rindex'): raise ValueError('__package__ set to non-string') if len(pkgname) == 0: if level > 0: raise ValueError('Attempted relative import in non-package') return None, '' name = pkgname else: # __package__ not set, so figure it out and set it if '__name__' not in globals: return None, '' modname = globals['__name__'] if '__path__' in globals: # __path__ is set, so modname is already the package name globals['__package__'] = name = modname else: # Normal module, so work out the package name if any lastdot = modname.rfind('.') if lastdot < 0 and level > 0: raise ValueError("Attempted relative import in non-package") if lastdot < 0: globals['__package__'] = None return None, '' globals['__package__'] = name = modname[:lastdot] dot = len(name) for x in xrange(level, 1, -1): try: dot = name.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") name = name[:dot] try: parent = sys.modules[name] except: if orig_level < 1: warn("Parent module '%.200s' not found while handling absolute " "import" % name) parent = None else: raise SystemError("Parent module '%.200s' not loaded, cannot " "perform relative import" % name) # We expect, but can't guarantee, if parent != None, that: # - parent.__name__ == name # - parent.__dict__ is globals # If this is violated... Who cares? return parent, name
mod name buf = load_next ( mod altmod name buf )
def load_next(mod, altmod, name, buf): """ mod, name, buf = load_next(mod, altmod, name, buf) altmod is either None or same as mod """ if len(name) == 0: # completely empty module name should only happen in # 'from . import' (or '__import__("")') return mod, None, buf dot = name.find('.') if dot == 0: raise ValueError('Empty module name') if dot < 0: subname = name next = None else: subname = name[:dot] next = name[dot+1:] if buf != '': buf += '.' buf += subname result = import_submodule(mod, subname, buf) if result is None and mod != altmod: result = import_submodule(altmod, subname, subname) if result is not None: buf = subname if result is None: raise ImportError("No module named %.200s" % name) return result, next, buf
m = import_submodule ( mod subname fullname )
def import_submodule(mod, subname, fullname): """m = import_submodule(mod, subname, fullname)""" # Require: # if mod == None: subname == fullname # else: mod.__name__ + "." + subname == fullname global found_now if fullname in found_now and fullname in sys.modules: m = sys.modules[fullname] else: print 'Reloading', fullname found_now[fullname] = 1 oldm = sys.modules.get(fullname, None) if mod is None: path = None elif hasattr(mod, '__path__'): path = mod.__path__ else: return None try: # This appears to be necessary on Python 3, because imp.find_module() # tries to import standard libraries (like io) itself, and we don't # want them to be processed by our deep_import_hook. with replace_import_hook(original_import): fp, filename, stuff = imp.find_module(subname, path) except ImportError: return None try: m = imp.load_module(fullname, fp, filename, stuff) except: # load_module probably removed name from modules because of # the error. Put back the original module object. if oldm: sys.modules[fullname] = oldm raise finally: if fp: fp.close() add_submodule(mod, m, fullname, subname) return m
mod. { subname } = submod
def add_submodule(mod, submod, fullname, subname): """mod.{subname} = submod""" if mod is None: return #Nothing to do here. if submod is None: submod = sys.modules[fullname] setattr(mod, subname, submod) return
Handle from module import a b c imports.
def ensure_fromlist(mod, fromlist, buf, recursive): """Handle 'from module import a, b, c' imports.""" if not hasattr(mod, '__path__'): return for item in fromlist: if not hasattr(item, 'rindex'): raise TypeError("Item in ``from list'' not a string") if item == '*': if recursive: continue # avoid endless recursion try: all = mod.__all__ except AttributeError: pass else: ret = ensure_fromlist(mod, all, buf, 1) if not ret: return 0 elif not hasattr(mod, item): import_submodule(mod, item, buf + '.' + item)
Replacement for __import__ ()
def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1): """Replacement for __import__()""" parent, buf = get_parent(globals, level) head, name, buf = load_next(parent, None if level < 0 else parent, name, buf) tail = head while name: tail, name, buf = load_next(tail, tail, name, buf) # If tail is None, both get_parent and load_next found # an empty module name: someone called __import__("") or # doctored faulty bytecode if tail is None: raise ValueError('Empty module name') if not fromlist: return head ensure_fromlist(tail, fromlist, buf, 0) return tail
Replacement for reload ().
def deep_reload_hook(m): """Replacement for reload().""" if not isinstance(m, ModuleType): raise TypeError("reload() argument must be module") name = m.__name__ if name not in sys.modules: raise ImportError("reload(): module %.200s not in sys.modules" % name) global modules_reloading try: return modules_reloading[name] except: modules_reloading[name] = m dot = name.rfind('.') if dot < 0: subname = name path = None else: try: parent = sys.modules[name[:dot]] except KeyError: modules_reloading.clear() raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot]) subname = name[dot+1:] path = getattr(parent, "__path__", None) try: # This appears to be necessary on Python 3, because imp.find_module() # tries to import standard libraries (like io) itself, and we don't # want them to be processed by our deep_import_hook. with replace_import_hook(original_import): fp, filename, stuff = imp.find_module(subname, path) finally: modules_reloading.clear() try: newm = imp.load_module(name, fp, filename, stuff) except: # load_module probably removed name from modules because of # the error. Put back the original module object. sys.modules[name] = m raise finally: if fp: fp.close() modules_reloading.clear() return newm
Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains sys __main__ and __builtin__ to prevent e. g. resetting display exception and io hooks.
def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']): """Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains sys, __main__, and __builtin__, to prevent, e.g., resetting display, exception, and io hooks. """ global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): ret = deep_reload_hook(module) finally: found_now = {} return ret
Compute a ( probably ) unique name for code for caching. This now expects code to be unicode.
def code_name(code, number=0): """ Compute a (probably) unique name for code for caching. This now expects code to be unicode. """ hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest() # Include the number and 12 characters of the hash in the name. It's # pretty much impossible that in a single session we'll have collisions # even with truncated hashes, and the full one makes tracebacks too long return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
Parse code to an AST with the current compiler flags active. Arguments are exactly the same as ast. parse ( in the standard library ) and are passed to the built - in compile function.
def ast_parse(self, source, filename='<unknown>', symbol='exec'): """Parse code to an AST with the current compiler flags active. Arguments are exactly the same as ast.parse (in the standard library), and are passed to the built-in compile function.""" return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
Make a name for a block of code and cache the code. Parameters ---------- code: str The Python source code to cache. number: int A number which forms part of the code s name. Used for the execution counter. Returns ------- The name of the cached code ( as a string ). Pass this as the filename argument to compilation so that tracebacks are correctly hooked up.
def cache(self, code, number=0): """Make a name for a block of code, and cache the code. Parameters ---------- code : str The Python source code to cache. number : int A number which forms part of the code's name. Used for the execution counter. Returns ------- The name of the cached code (as a string). Pass this as the filename argument to compilation, so that tracebacks are correctly hooked up. """ name = code_name(code, number) entry = (len(code), time.time(), [line+'\n' for line in code.splitlines()], name) linecache.cache[name] = entry linecache._ipython_cache[name] = entry return name
Call linecache. checkcache () safely protecting our cached values.
def check_cache(self, *args): """Call linecache.checkcache() safely protecting our cached values. """ # First call the orignal checkcache as intended linecache._checkcache_ori(*args) # Then, update back the cache with our data, so that tracebacks related # to our compiled codes can be produced. linecache.cache.update(linecache._ipython_cache)
Add a line of source to the code.
def add_line(self, line): """Add a line of source to the code. Don't include indentations or newlines. """ self.code.append(" " * self.indent_amount) self.code.append(line) self.code.append("\n")
Add a section a sub - CodeBuilder.
def add_section(self): """Add a section, a sub-CodeBuilder.""" sect = CodeBuilder(self.indent_amount) self.code.append(sect) return sect
Compile the code and return the function fn_name.
def get_function(self, fn_name): """Compile the code, and return the function `fn_name`.""" assert self.indent_amount == 0 g = {} code_text = str(self) exec(code_text, g) return g[fn_name]
Generate a Python expression for expr.
def expr_code(self, expr): """Generate a Python expression for `expr`.""" if "|" in expr: pipes = expr.split("|") code = self.expr_code(pipes[0]) for func in pipes[1:]: self.all_vars.add(func) code = "c_%s(%s)" % (func, code) elif "." in expr: dots = expr.split(".") code = self.expr_code(dots[0]) args = [repr(d) for d in dots[1:]] code = "dot(%s, %s)" % (code, ", ".join(args)) else: self.all_vars.add(expr) code = "c_%s" % expr return code
Render this template by applying it to context.
def render(self, context=None): """Render this template by applying it to `context`. `context` is a dictionary of values to use in this rendering. """ # Make the complete context we'll use. ctx = dict(self.context) if context: ctx.update(context) return self.render_function(ctx, self.do_dots)
Evaluate dotted expressions at runtime.
def do_dots(self, value, *dots): """Evaluate dotted expressions at runtime.""" for dot in dots: try: value = getattr(value, dot) except AttributeError: value = value[dot] if hasattr(value, '__call__'): value = value() return value
A shortcut function to render a partial template with context and return the output.
def render_template(tpl, context): ''' A shortcut function to render a partial template with context and return the output. ''' templates = [tpl] if type(tpl) != list else tpl tpl_instance = None for tpl in templates: try: tpl_instance = template.loader.get_template(tpl) break except template.TemplateDoesNotExist: pass if not tpl_instance: raise Exception('Template does not exist: ' + templates[-1]) return tpl_instance.render(template.Context(context))
Return a format data dict for an object.
def format_display_data(obj, include=None, exclude=None): """Return a format data dict for an object. By default all format types will be computed. The following MIME types are currently implemented: * text/plain * text/html * text/latex * application/json * application/javascript * image/png * image/jpeg * image/svg+xml Parameters ---------- obj : object The Python object whose format data will be computed. Returns ------- format_dict : dict A dictionary of key/value pairs, one or each format that was generated for the object. The keys are the format types, which will usually be MIME type strings and the values and JSON'able data structure containing the raw data for the representation in that format. include : list or tuple, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list or tuple, optional A list of format type string (MIME types) to exclue in the format data dict. If this is set all format types will be computed, except for those included in this argument. """ from IPython.core.interactiveshell import InteractiveShell InteractiveShell.instance().display_formatter.format( obj, include, exclude )
Activate the default formatters.
def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, SVGFormatter, PNGFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, JavascriptFormatter ] d = {} for cls in formatter_classes: f = cls(config=self.config) d[f.format_type] = f return d
Return a format data dict for an object.
def format(self, obj, include=None, exclude=None): """Return a format data dict for an object. By default all format types will be computed. The following MIME types are currently implemented: * text/plain * text/html * text/latex * application/json * application/javascript * image/png * image/jpeg * image/svg+xml Parameters ---------- obj : object The Python object whose format data will be computed. include : list or tuple, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list or tuple, optional A list of format type string (MIME types) to exclue in the format data dict. If this is set all format types will be computed, except for those included in this argument. Returns ------- format_dict : dict A dictionary of key/value pairs, one or each format that was generated for the object. The keys are the format types, which will usually be MIME type strings and the values and JSON'able data structure containing the raw data for the representation in that format. """ format_dict = {} # If plain text only is active if self.plain_text_only: formatter = self.formatters['text/plain'] try: data = formatter(obj) except: # FIXME: log the exception raise if data is not None: format_dict['text/plain'] = data return format_dict for format_type, formatter in self.formatters.items(): if include is not None: if format_type not in include: continue if exclude is not None: if format_type in exclude: continue try: data = formatter(obj) except: # FIXME: log the exception raise if data is not None: format_dict[format_type] = data return format_dict
Add a format function for a given type.
def for_type(self, typ, func): """Add a format function for a given type. Parameters ----------- typ : class The class of the object that will be formatted using `func`. func : callable The callable that will be called to compute the format data. The call signature of this function is simple, it must take the object to be formatted and return the raw data for the given format. Subclasses may use a different call signature for the `func` argument. """ oldfunc = self.type_printers.get(typ, None) if func is not None: # To support easy restoration of old printers, we need to ignore # Nones. self.type_printers[typ] = func return oldfunc
Add a format function for a type specified by the full dotted module and name of the type rather than the type of the object.
def for_type_by_name(self, type_module, type_name, func): """Add a format function for a type specified by the full dotted module and name of the type, rather than the type of the object. Parameters ---------- type_module : str The full dotted name of the module the type is defined in, like ``numpy``. type_name : str The name of the type (the class name), like ``dtype`` func : callable The callable that will be called to compute the format data. The call signature of this function is simple, it must take the object to be formatted and return the raw data for the given format. Subclasses may use a different call signature for the `func` argument. """ key = (type_module, type_name) oldfunc = self.deferred_printers.get(key, None) if func is not None: # To support easy restoration of old printers, we need to ignore # Nones. self.deferred_printers[key] = func return oldfunc
Check if the given class is specified in the deferred type registry.
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future use. """ mod = getattr(cls, '__module__', None) name = getattr(cls, '__name__', None) key = (mod, name) printer = None if key in self.deferred_printers: # Move the printer over to the regular registry. printer = self.deferred_printers.pop(key) self.type_printers[cls] = printer return printer
float_precision changed set float_format accordingly.
def _float_precision_changed(self, name, old, new): """float_precision changed, set float_format accordingly. float_precision can be set by int or str. This will set float_format, after interpreting input. If numpy has been imported, numpy print precision will also be set. integer `n` sets format to '%.nf', otherwise, format set directly. An empty string returns to defaults (repr for float, 8 for numpy). This parameter can be set via the '%precision' magic. """ if '%' in new: # got explicit format string fmt = new try: fmt%3.14159 except Exception: raise ValueError("Precision must be int or format string, not %r"%new) elif new: # otherwise, should be an int try: i = int(new) assert i >= 0 except ValueError: raise ValueError("Precision must be int or format string, not %r"%new) except AssertionError: raise ValueError("int precision must be non-negative, not %r"%i) fmt = '%%.%if'%i if 'numpy' in sys.modules: # set numpy precision if it has been imported import numpy numpy.set_printoptions(precision=i) else: # default back to repr fmt = '%r' if 'numpy' in sys.modules: import numpy # numpy default is 8 numpy.set_printoptions(precision=8) self.float_format = fmt
Return path to any existing user config files
def user_config_files(): """Return path to any existing user config files """ return filter(os.path.exists, map(os.path.expanduser, config_files))
Does the value look like an on/ off flag?
def flag(val): """Does the value look like an on/off flag?""" if val == 1: return True elif val == 0: return False val = str(val) if len(val) > 5: return False return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF')
Configure the nose running environment. Execute configure before collecting tests with nose. TestCollector to enable output capture and other features.
def configure(self, argv=None, doc=None): """Configure the nose running environment. Execute configure before collecting tests with nose.TestCollector to enable output capture and other features. """ env = self.env if argv is None: argv = sys.argv cfg_files = getattr(self, 'files', []) options, args = self._parseArgs(argv, cfg_files) # If -c --config has been specified on command line, # load those config files and reparse if getattr(options, 'files', []): options, args = self._parseArgs(argv, options.files) self.options = options if args: self.testNames = args if options.testNames is not None: self.testNames.extend(tolist(options.testNames)) if options.py3where is not None: if sys.version_info >= (3,): options.where = options.py3where # `where` is an append action, so it can't have a default value # in the parser, or that default will always be in the list if not options.where: options.where = env.get('NOSE_WHERE', None) # include and exclude also if not options.ignoreFiles: options.ignoreFiles = env.get('NOSE_IGNORE_FILES', []) if not options.include: options.include = env.get('NOSE_INCLUDE', []) if not options.exclude: options.exclude = env.get('NOSE_EXCLUDE', []) self.addPaths = options.addPaths self.stopOnError = options.stopOnError self.verbosity = options.verbosity self.includeExe = options.includeExe self.traverseNamespace = options.traverseNamespace self.debug = options.debug self.debugLog = options.debugLog self.loggingConfig = options.loggingConfig self.firstPackageWins = options.firstPackageWins self.configureLogging() if options.where is not None: self.configureWhere(options.where) if options.testMatch: self.testMatch = re.compile(options.testMatch) if options.ignoreFiles: self.ignoreFiles = map(re.compile, tolist(options.ignoreFiles)) log.info("Ignoring files matching %s", options.ignoreFiles) else: log.info("Ignoring files matching %s", self.ignoreFilesDefaultStrings) if options.include: self.include = map(re.compile, tolist(options.include)) log.info("Including tests matching %s", options.include) if options.exclude: self.exclude = map(re.compile, tolist(options.exclude)) log.info("Excluding tests matching %s", options.exclude) # When listing plugins we don't want to run them if not options.showPlugins: self.plugins.configure(options, self) self.plugins.begin()
Configure logging for nose or optionally other packages. Any logger name may be set with the debug option and that logger will be set to debug level and be assigned the same handler as the nose loggers unless it already has a handler.
def configureLogging(self): """Configure logging for nose, or optionally other packages. Any logger name may be set with the debug option, and that logger will be set to debug level and be assigned the same handler as the nose loggers, unless it already has a handler. """ if self.loggingConfig: from logging.config import fileConfig fileConfig(self.loggingConfig) return format = logging.Formatter('%(name)s: %(levelname)s: %(message)s') if self.debugLog: handler = logging.FileHandler(self.debugLog) else: handler = logging.StreamHandler(self.logStream) handler.setFormatter(format) logger = logging.getLogger('nose') logger.propagate = 0 # only add our default handler if there isn't already one there # this avoids annoying duplicate log messages. if handler not in logger.handlers: logger.addHandler(handler) # default level lvl = logging.WARNING if self.verbosity >= 5: lvl = 0 elif self.verbosity >= 4: lvl = logging.DEBUG elif self.verbosity >= 3: lvl = logging.INFO logger.setLevel(lvl) # individual overrides if self.debug: # no blanks debug_loggers = [ name for name in self.debug.split(',') if name ] for logger_name in debug_loggers: l = logging.getLogger(logger_name) l.setLevel(logging.DEBUG) if not l.handlers and not logger_name.startswith('nose'): l.addHandler(handler)
Configure the working directory or directories for the test run.
def configureWhere(self, where): """Configure the working directory or directories for the test run. """ from nose.importer import add_path self.workingDir = None where = tolist(where) warned = False for path in where: if not self.workingDir: abs_path = absdir(path) if abs_path is None: raise ValueError("Working directory %s not found, or " "not a directory" % path) log.info("Set working dir to %s", abs_path) self.workingDir = abs_path if self.addPaths and \ os.path.exists(os.path.join(abs_path, '__init__.py')): log.info("Working directory %s is a package; " "adding to sys.path" % abs_path) add_path(abs_path) continue if not warned: warn("Use of multiple -w arguments is deprecated and " "support may be removed in a future release. You can " "get the same behavior by passing directories without " "the -w argument on the command line, or by using the " "--tests argument in a configuration file.", DeprecationWarning) self.testNames.append(path)
Get the command line option parser.
def getParser(self, doc=None): """Get the command line option parser. """ if self.parser: return self.parser env = self.env parser = self.parserClass(doc) parser.add_option( "-V","--version", action="store_true", dest="version", default=False, help="Output nose version and exit") parser.add_option( "-p", "--plugins", action="store_true", dest="showPlugins", default=False, help="Output list of available plugins and exit. Combine with " "higher verbosity for greater detail") parser.add_option( "-v", "--verbose", action="count", dest="verbosity", default=self.verbosity, help="Be more verbose. [NOSE_VERBOSE]") parser.add_option( "--verbosity", action="store", dest="verbosity", metavar='VERBOSITY', type="int", help="Set verbosity; --verbosity=2 is " "the same as -v") parser.add_option( "-q", "--quiet", action="store_const", const=0, dest="verbosity", help="Be less verbose") parser.add_option( "-c", "--config", action="append", dest="files", metavar="FILES", help="Load configuration from config file(s). May be specified " "multiple times; in that case, all config files will be " "loaded and combined") parser.add_option( "-w", "--where", action="append", dest="where", metavar="WHERE", help="Look for tests in this directory. " "May be specified multiple times. The first directory passed " "will be used as the working directory, in place of the current " "working directory, which is the default. Others will be added " "to the list of tests to execute. [NOSE_WHERE]" ) parser.add_option( "--py3where", action="append", dest="py3where", metavar="PY3WHERE", help="Look for tests in this directory under Python 3.x. " "Functions the same as 'where', but only applies if running under " "Python 3.x or above. Note that, if present under 3.x, this " "option completely replaces any directories specified with " "'where', so the 'where' option becomes ineffective. " "[NOSE_PY3WHERE]" ) parser.add_option( "-m", "--match", "--testmatch", action="store", dest="testMatch", metavar="REGEX", help="Files, directories, function names, and class names " "that match this regular expression are considered tests. " "Default: %s [NOSE_TESTMATCH]" % self.testMatchPat, default=self.testMatchPat) parser.add_option( "--tests", action="store", dest="testNames", default=None, metavar='NAMES', help="Run these tests (comma-separated list). This argument is " "useful mainly from configuration files; on the command line, " "just pass the tests to run as additional arguments with no " "switch.") parser.add_option( "-l", "--debug", action="store", dest="debug", default=self.debug, help="Activate debug logging for one or more systems. " "Available debug loggers: nose, nose.importer, " "nose.inspector, nose.plugins, nose.result and " "nose.selector. Separate multiple names with a comma.") parser.add_option( "--debug-log", dest="debugLog", action="store", default=self.debugLog, metavar="FILE", help="Log debug messages to this file " "(default: sys.stderr)") parser.add_option( "--logging-config", "--log-config", dest="loggingConfig", action="store", default=self.loggingConfig, metavar="FILE", help="Load logging config from this file -- bypasses all other" " logging config settings.") parser.add_option( "-I", "--ignore-files", action="append", dest="ignoreFiles", metavar="REGEX", help="Completely ignore any file that matches this regular " "expression. Takes precedence over any other settings or " "plugins. " "Specifying this option will replace the default setting. " "Specify this option multiple times " "to add more regular expressions [NOSE_IGNORE_FILES]") parser.add_option( "-e", "--exclude", action="append", dest="exclude", metavar="REGEX", help="Don't run tests that match regular " "expression [NOSE_EXCLUDE]") parser.add_option( "-i", "--include", action="append", dest="include", metavar="REGEX", help="This regular expression will be applied to files, " "directories, function names, and class names for a chance " "to include additional tests that do not match TESTMATCH. " "Specify this option multiple times " "to add more regular expressions [NOSE_INCLUDE]") parser.add_option( "-x", "--stop", action="store_true", dest="stopOnError", default=self.stopOnError, help="Stop running tests after the first error or failure") parser.add_option( "-P", "--no-path-adjustment", action="store_false", dest="addPaths", default=self.addPaths, help="Don't make any changes to sys.path when " "loading tests [NOSE_NOPATH]") parser.add_option( "--exe", action="store_true", dest="includeExe", default=self.includeExe, help="Look for tests in python modules that are " "executable. Normal behavior is to exclude executable " "modules, since they may not be import-safe " "[NOSE_INCLUDE_EXE]") parser.add_option( "--noexe", action="store_false", dest="includeExe", help="DO NOT look for tests in python modules that are " "executable. (The default on the windows platform is to " "do so.)") parser.add_option( "--traverse-namespace", action="store_true", default=self.traverseNamespace, dest="traverseNamespace", help="Traverse through all path entries of a namespace package") parser.add_option( "--first-package-wins", "--first-pkg-wins", "--1st-pkg-wins", action="store_true", default=False, dest="firstPackageWins", help="nose's importer will normally evict a package from sys." "modules if it sees a package with the same name in a different " "location. Set this option to disable that behavior.") self.plugins.loadPlugins() self.pluginOpts(parser) self.parser = parser return parser
Very dumb pager in Python for when nothing else works.
def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and mode.""" out_ln = strng.splitlines()[start:] screens = chop(out_ln,screen_lines-1) if len(screens) == 1: print >>io.stdout, os.linesep.join(screens[0]) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print >>io.stdout, last_escape + hunk if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print >>io.stdout, last_escape + os.linesep.join(screens[-1])
Attempt to work out the number of lines on the screen. This is called by page (). It can raise an error ( e. g. when run in the test suite ) so it s separated out so it can easily be called in a try block.
def _detect_screen_size(use_curses, screen_lines_def): """Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM',None) if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5': local_use_curses = use_curses else: # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. local_use_curses = False if local_use_curses: import termios import curses # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check everytime for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. term_flags = termios.tcgetattr(sys.stdout) # Curses modifies the stdout buffer size by default, which messes # up Python's normal stdout buffering. This would manifest itself # to IPython users as delayed printing on stdout after having used # the pager. # # We can prevent this by manually setting the NCURSES_NO_SETBUF # environment variable. For more details, see: # http://bugs.python.org/issue10144 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) os.environ['NCURSES_NO_SETBUF'] = '' # Proceed with curses initialization scr = curses.initscr() screen_lines_real,screen_cols = scr.getmaxyx() curses.endwin() # Restore environment if NCURSES_NO_SETBUF is None: del os.environ['NCURSES_NO_SETBUF'] else: os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF # Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real #print '***Screen size:',screen_lines_real,'lines x',\ #screen_cols,'columns.' # dbg else: return screen_lines_def
Print a string piping through a pager after a certain length.
def page(strng, start=0, screen_lines=0, pager_cmd=None): """Print a string, piping through a pager after a certain length. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0. If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less. If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) # first, try the hook ip = ipapi.get() if ip: try: ip.hooks.show_in_pager(strng) return except TryNext: pass # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM','dumb') if TERM in ['dumb','emacs'] and os.name != 'nt': print strng return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint) # Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines,int(len_str/80)+1) screen_lines_def = get_terminal_size()[1] # auto-determine screen size if screen_lines <= 0: try: screen_lines += _detect_screen_size(use_curses, screen_lines_def) except (TypeError, UnsupportedOperation): print >>io.stdout, str_toprint return #print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines : #print '*** normal print' # dbg print >>io.stdout, str_toprint else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd,start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex strings. retval = 1 else: tmpname = tempfile.mktemp('.txt') tmpfile = open(tmpname,'wt') tmpfile.write(strng) tmpfile.close() cmd = "%s < %s" % (pager_cmd,tmpname) if os.system(cmd): retval = 1 else: retval = None os.remove(tmpname) else: try: retval = None # if I use popen4, things hang. No idea why. #pager,shell_out = os.popen4(pager_cmd) pager = os.popen(pager_cmd,'w') pager.write(strng) pager.close() retval = pager.close() # success returns None except IOError,msg: # broken pipe when user quits if msg.args == (32,'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng,screen_lines=screen_lines)
Page a file using an optional pager command and starting line.
def page_file(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """ pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd,start) try: if os.environ['TERM'] in ['emacs','dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname).read(),start) except: print 'Unable to show file',`fname`
Return a pager command.
def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt','dos']: default_pager_cmd = 'type' if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd return pager_cmd
Return the string for paging files with an offset.
def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less','more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string
Print a string snipping the midsection to fit in width.
def snip_print(str,width = 75,print_full = 0,header = ''): """Print a string snipping the midsection to fit in width. print_full: mode control: - 0: only snip long strings - 1: send to page() directly. - 2: snip long strings and ask for full length viewing with page() Return 1 if snipping was necessary, 0 otherwise.""" if print_full == 1: page(header+str) return 0 print header, if len(str) < width: print str snip = 0 else: whalf = int((width -5)/2) print str[:whalf] + ' <...> ' + str[-whalf:] snip = 1 if snip and print_full == 2: if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': page(str) return snip
timings_out ( reps func * args ** kw ) - > ( t_total t_per_call output )
def timings_out(reps,func,*args,**kw): """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds, the time per call and the function's output. Under Unix, the return value is the sum of user+system time consumed by the process, computed via the resource module. This prevents problems related to the wraparound effect which the time.clock() function has. Under Windows the return value is in wall clock seconds. See the documentation for the time module for more details.""" reps = int(reps) assert reps >=1, 'reps must be >= 1' if reps==1: start = clock() out = func(*args,**kw) tot_time = clock()-start else: rng = xrange(reps-1) # the last time is executed separately to store output start = clock() for dummy in rng: func(*args,**kw) out = func(*args,**kw) # one last time tot_time = clock()-start av_time = tot_time / reps return tot_time,av_time,out
timings ( reps func * args ** kw ) - > ( t_total t_per_call )
def timings(reps,func,*args,**kw): """timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out().""" return timings_out(reps,func,*args,**kw)[0:2]
A function to pretty print sympy Basic objects.
def print_basic_unicode(o, p, cycle): """A function to pretty print sympy Basic objects.""" if cycle: return p.text('Basic(...)') out = pretty(o, use_unicode=True) if '\n' in out: p.text(u'\n') p.text(out)
A function to display sympy expression using inline style LaTeX in PNG.
def print_png(o): """ A function to display sympy expression using inline style LaTeX in PNG. """ s = latex(o, mode='inline') # mathtext does not understand certain latex flags, so we try to replace # them with suitable subs. s = s.replace('\\operatorname','') s = s.replace('\\overline', '\\bar') png = latex_to_png(s) return png
A function to display sympy expression using display style LaTeX in PNG.
def print_display_png(o): """ A function to display sympy expression using display style LaTeX in PNG. """ s = latex(o, mode='plain') s = s.strip('$') # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png('$$%s$$' % s, backend='dvipng') return png
Return True if type o can be printed with LaTeX.
def can_print_latex(o): """ Return True if type o can be printed with LaTeX. If o is a container type, this is True if and only if every element of o can be printed with LaTeX. """ import sympy if isinstance(o, (list, tuple, set, frozenset)): return all(can_print_latex(i) for i in o) elif isinstance(o, dict): return all((isinstance(i, basestring) or can_print_latex(i)) and can_print_latex(o[i]) for i in o) elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)): return True return False
A function to generate the latex representation of sympy expressions.
def print_latex(o): """A function to generate the latex representation of sympy expressions.""" if can_print_latex(o): s = latex(o, mode='plain') s = s.replace('\\dag','\\dagger') s = s.strip('$') return '$$%s$$' % s # Fallback to the string printer return None
Load the extension in IPython.
def load_ipython_extension(ip): """Load the extension in IPython.""" import sympy # sympyprinting extension has been moved to SymPy as of 0.7.2, if it # exists there, warn the user and import it try: import sympy.interactive.ipythonprinting except ImportError: pass else: warnings.warn("The sympyprinting extension in IPython is deprecated, " "use sympy.interactive.ipythonprinting") ip.extension_manager.load_extension('sympy.interactive.ipythonprinting') return global _loaded if not _loaded: plaintext_formatter = ip.display_formatter.formatters['text/plain'] for cls in (object, str): plaintext_formatter.for_type(cls, print_basic_unicode) printable_containers = [list, tuple] # set and frozen set were broken with SymPy's latex() function, but # was fixed in the 0.7.1-git development version. See # http://code.google.com/p/sympy/issues/detail?id=3062. if sympy.__version__ > '0.7.1': printable_containers += [set, frozenset] else: plaintext_formatter.for_type(cls, print_basic_unicode) plaintext_formatter.for_type_by_name( 'sympy.core.basic', 'Basic', print_basic_unicode ) plaintext_formatter.for_type_by_name( 'sympy.matrices.matrices', 'Matrix', print_basic_unicode ) png_formatter = ip.display_formatter.formatters['image/png'] png_formatter.for_type_by_name( 'sympy.core.basic', 'Basic', print_png ) png_formatter.for_type_by_name( 'sympy.matrices.matrices', 'Matrix', print_display_png ) for cls in [dict, int, long, float] + printable_containers: png_formatter.for_type(cls, print_png) latex_formatter = ip.display_formatter.formatters['text/latex'] latex_formatter.for_type_by_name( 'sympy.core.basic', 'Basic', print_latex ) latex_formatter.for_type_by_name( 'sympy.matrices.matrices', 'Matrix', print_latex ) for cls in printable_containers: # Use LaTeX only if every element is printable by latex latex_formatter.for_type(cls, print_latex) _loaded = True
Usage: { % with this is a string |str2tokens: as token_list % } do something { % endwith % }
def str2tokens(string, delimiter): """ Usage: {% with 'this, is a, string'|str2tokens:',' as token_list %}do something{% endwith %} """ token_list = [token.strip() for token in string.split(delimiter)] return token_list
Usage: { % str2tokens a/ b/ c/ d/ as token_list % }
def str2tokenstags(string, delimiter): """ Usage: {% str2tokens 'a/b/c/d' '/' as token_list %} """ token_list = [token.strip() for token in string.split(delimiter)] return token_list
Non - camel - case version of func name for backwards compatibility.
def add_options(self, parser, env=None): """Non-camel-case version of func name for backwards compatibility. .. warning :: DEPRECATED: Do not use this method, use :meth:`options <nose.plugins.base.IPluginInterface.options>` instead. """ # FIXME raise deprecation warning if wasn't called by wrapper if env is None: env = os.environ try: self.options(parser, env) self.can_configure = True except OptionConflictError, e: warn("Plugin %s has conflicting option string: %s and will " "be disabled" % (self, e), RuntimeWarning) self.enabled = False self.can_configure = False
Register commandline options.
def options(self, parser, env): """Register commandline options. Implement this method for normal options behavior with protection from OptionConflictErrors. If you override this method and want the default --with-$name option to be registered, be sure to call super(). """ env_opt = 'NOSE_WITH_%s' % self.name.upper() env_opt = env_opt.replace('-', '_') parser.add_option("--with-%s" % self.name, action="store_true", dest=self.enableOpt, default=env.get(env_opt), help="Enable plugin %s: %s [%s]" % (self.__class__.__name__, self.help(), env_opt))
Configure the plugin and system based on selected options.
def configure(self, options, conf): """Configure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable option for the plugin (self.enableOpt) is true. """ if not self.can_configure: return self.conf = conf if hasattr(options, self.enableOpt): self.enabled = getattr(options, self.enableOpt)
Validate that the input is a list of strings.
def validate_string_list(lst): """Validate that the input is a list of strings. Raises ValueError if not.""" if not isinstance(lst, list): raise ValueError('input %r must be a list' % lst) for x in lst: if not isinstance(x, basestring): raise ValueError('element %r in list must be a string' % x)
Validate that the input is a dict with string keys and values.
def validate_string_dict(dct): """Validate that the input is a dict with string keys and values. Raises ValueError if not.""" for k,v in dct.iteritems(): if not isinstance(k, basestring): raise ValueError('key %r in dict must be a string' % k) if not isinstance(v, basestring): raise ValueError('value %r in dict must be a string' % v)
Run my loop ignoring EINTR events in the poller
def _run_loop(self): """Run my loop, ignoring EINTR events in the poller""" while True: try: self.ioloop.start() except ZMQError as e: if e.errno == errno.EINTR: continue else: raise except Exception: if self._exiting: break else: raise else: break
Queue a message to be sent from the IOLoop s thread. Parameters ---------- msg: message to send This is threadsafe as it uses IOLoop. add_callback to give the loop s thread control of the action.
def _queue_send(self, msg): """Queue a message to be sent from the IOLoop's thread. Parameters ---------- msg : message to send This is threadsafe, as it uses IOLoop.add_callback to give the loop's thread control of the action. """ def thread_send(): self.session.send(self.stream, msg) self.ioloop.add_callback(thread_send)
callback for stream. on_recv unpacks message and calls handlers with it.
def _handle_recv(self, msg): """callback for stream.on_recv unpacks message, and calls handlers with it. """ ident,smsg = self.session.feed_identities(msg) self.call_handlers(self.session.unserialize(smsg))
The thread s main activity. Call start () instead.
def run(self): """The thread's main activity. Call start() instead.""" self.socket = self.context.socket(zmq.DEALER) self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) self.socket.connect('tcp://%s:%i' % self.address) self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) self.stream.on_recv(self._handle_recv) self._run_loop() try: self.socket.close() except: pass
Execute code in the kernel.
def execute(self, code, silent=False, user_variables=None, user_expressions=None, allow_stdin=None): """Execute code in the kernel. Parameters ---------- code : str A string of Python code. silent : bool, optional (default False) If set, the kernel will execute the code as quietly possible. user_variables : list, optional A list of variable names to pull from the user's namespace. They will come back as a dict with these names as keys and their :func:`repr` as values. user_expressions : dict, optional A dict with string keys and to pull from the user's namespace. They will come back as a dict with these names as keys and their :func:`repr` as values. allow_stdin : bool, optional Flag for A dict with string keys and to pull from the user's namespace. They will come back as a dict with these names as keys and their :func:`repr` as values. Returns ------- The msg_id of the message sent. """ if user_variables is None: user_variables = [] if user_expressions is None: user_expressions = {} if allow_stdin is None: allow_stdin = self.allow_stdin # Don't waste network traffic if inputs are invalid if not isinstance(code, basestring): raise ValueError('code %r must be a string' % code) validate_string_list(user_variables) validate_string_dict(user_expressions) # Create class for content/msg creation. Related to, but possibly # not in Session. content = dict(code=code, silent=silent, user_variables=user_variables, user_expressions=user_expressions, allow_stdin=allow_stdin, ) msg = self.session.msg('execute_request', content) self._queue_send(msg) return msg['header']['msg_id']
Tab complete text in the kernel s namespace.
def complete(self, text, line, cursor_pos, block=None): """Tab complete text in the kernel's namespace. Parameters ---------- text : str The text to complete. line : str The full line of text that is the surrounding context for the text to complete. cursor_pos : int The position of the cursor in the line where the completion was requested. block : str, optional The full block of code in which the completion is being requested. Returns ------- The msg_id of the message sent. """ content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos) msg = self.session.msg('complete_request', content) self._queue_send(msg) return msg['header']['msg_id']
Get metadata information about an object.
def object_info(self, oname, detail_level=0): """Get metadata information about an object. Parameters ---------- oname : str A string specifying the object name. detail_level : int, optional The level of detail for the introspection (0-2) Returns ------- The msg_id of the message sent. """ content = dict(oname=oname, detail_level=detail_level) msg = self.session.msg('object_info_request', content) self._queue_send(msg) return msg['header']['msg_id']
Get entries from the history list.
def history(self, raw=True, output=False, hist_access_type='range', **kwargs): """Get entries from the history list. Parameters ---------- raw : bool If True, return the raw input. output : bool If True, then return the output as well. hist_access_type : str 'range' (fill in session, start and stop params), 'tail' (fill in n) or 'search' (fill in pattern param). session : int For a range request, the session from which to get lines. Session numbers are positive integers; negative ones count back from the current session. start : int The first line number of a history range. stop : int The final (excluded) line number of a history range. n : int The number of lines of history to get for a tail request. pattern : str The glob-syntax pattern for a search request. Returns ------- The msg_id of the message sent. """ content = dict(raw=raw, output=output, hist_access_type=hist_access_type, **kwargs) msg = self.session.msg('history_request', content) self._queue_send(msg) return msg['header']['msg_id']
Request an immediate kernel shutdown.
def shutdown(self, restart=False): """Request an immediate kernel shutdown. Upon receipt of the (empty) reply, client code can safely assume that the kernel has shut down and it's safe to forcefully terminate it if it's still alive. The kernel will send the reply via a function registered with Python's atexit module, ensuring it's truly done as the kernel is done with all normal operation. """ # Send quit message to kernel. Once we implement kernel-side setattr, # this should probably be done that way, but for now this will do. msg = self.session.msg('shutdown_request', {'restart':restart}) self._queue_send(msg) return msg['header']['msg_id']
Immediately processes all pending messages on the SUB channel.
def flush(self, timeout=1.0): """Immediately processes all pending messages on the SUB channel. Callers should use this method to ensure that :method:`call_handlers` has been called for all messages that have been received on the 0MQ SUB socket of this channel. This method is thread safe. Parameters ---------- timeout : float, optional The maximum amount of time to spend flushing, in seconds. The default is one second. """ # We do the IOLoop callback process twice to ensure that the IOLoop # gets to perform at least one full poll. stop_time = time.time() + timeout for i in xrange(2): self._flushed = False self.ioloop.add_callback(self._flush) while not self._flushed and time.time() < stop_time: time.sleep(0.01)
Send a string of raw input to the kernel.
def input(self, string): """Send a string of raw input to the kernel.""" content = dict(value=string) msg = self.session.msg('input_reply', content) self._queue_send(msg)
poll for heartbeat replies until we reach self. time_to_dead Ignores interrupts and returns the result of poll () which will be an empty list if no messages arrived before the timeout or the event tuple if there is a message to receive.
def _poll(self, start_time): """poll for heartbeat replies until we reach self.time_to_dead Ignores interrupts, and returns the result of poll(), which will be an empty list if no messages arrived before the timeout, or the event tuple if there is a message to receive. """ until_dead = self.time_to_dead - (time.time() - start_time) # ensure poll at least once until_dead = max(until_dead, 1e-3) events = [] while True: try: events = self.poller.poll(1000 * until_dead) except ZMQError as e: if e.errno == errno.EINTR: # ignore interrupts during heartbeat # this may never actually happen until_dead = self.time_to_dead - (time.time() - start_time) until_dead = max(until_dead, 1e-3) pass else: raise except Exception: if self._exiting: break else: raise else: break return events
The thread s main activity. Call start () instead.
def run(self): """The thread's main activity. Call start() instead.""" self._create_socket() self._running = True self._beating = True while self._running: if self._pause: # just sleep, and skip the rest of the loop time.sleep(self.time_to_dead) continue since_last_heartbeat = 0.0 # io.rprint('Ping from HB channel') # dbg # no need to catch EFSM here, because the previous event was # either a recv or connect, which cannot be followed by EFSM self.socket.send(b'ping') request_time = time.time() ready = self._poll(request_time) if ready: self._beating = True # the poll above guarantees we have something to recv self.socket.recv() # sleep the remainder of the cycle remainder = self.time_to_dead - (time.time() - request_time) if remainder > 0: time.sleep(remainder) continue else: # nothing was received within the time limit, signal heart failure self._beating = False since_last_heartbeat = time.time() - request_time self.call_handlers(since_last_heartbeat) # and close/reopen the socket, because the REQ/REP cycle has been broken self._create_socket() continue try: self.socket.close() except: pass
Is the heartbeat running and responsive ( and not paused ).
def is_beating(self): """Is the heartbeat running and responsive (and not paused).""" if self.is_alive() and not self._pause and self._beating: return True else: return False
Starts the channels for this kernel.
def start_channels(self, shell=True, sub=True, stdin=True, hb=True): """Starts the channels for this kernel. This will create the channels if they do not exist and then start them. If port numbers of 0 are being used (random ports) then you must first call :method:`start_kernel`. If the channels have been stopped and you call this, :class:`RuntimeError` will be raised. """ if shell: self.shell_channel.start() if sub: self.sub_channel.start() if stdin: self.stdin_channel.start() self.shell_channel.allow_stdin = True else: self.shell_channel.allow_stdin = False if hb: self.hb_channel.start()
Stops all the running channels for this kernel.
def stop_channels(self): """Stops all the running channels for this kernel. """ if self.shell_channel.is_alive(): self.shell_channel.stop() if self.sub_channel.is_alive(): self.sub_channel.stop() if self.stdin_channel.is_alive(): self.stdin_channel.stop() if self.hb_channel.is_alive(): self.hb_channel.stop()
Are any of the channels created and running?
def channels_running(self): """Are any of the channels created and running?""" return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or self.stdin_channel.is_alive() or self.hb_channel.is_alive())
cleanup connection file * if we wrote it * Will not raise if the connection file was already removed somehow.
def cleanup_connection_file(self): """cleanup connection file *if we wrote it* Will not raise if the connection file was already removed somehow. """ if self._connection_file_written: # cleanup connection files on full shutdown of kernel we started self._connection_file_written = False try: os.remove(self.connection_file) except OSError: pass
load connection info from JSON dict in self. connection_file
def load_connection_file(self): """load connection info from JSON dict in self.connection_file""" with open(self.connection_file) as f: cfg = json.loads(f.read()) self.ip = cfg['ip'] self.shell_port = cfg['shell_port'] self.stdin_port = cfg['stdin_port'] self.iopub_port = cfg['iopub_port'] self.hb_port = cfg['hb_port'] self.session.key = str_to_bytes(cfg['key'])
write connection info to JSON dict in self. connection_file
def write_connection_file(self): """write connection info to JSON dict in self.connection_file""" if self._connection_file_written: return self.connection_file,cfg = write_connection_file(self.connection_file, ip=self.ip, key=self.session.key, stdin_port=self.stdin_port, iopub_port=self.iopub_port, shell_port=self.shell_port, hb_port=self.hb_port) # write_connection_file also sets default ports: self.shell_port = cfg['shell_port'] self.stdin_port = cfg['stdin_port'] self.iopub_port = cfg['iopub_port'] self.hb_port = cfg['hb_port'] self._connection_file_written = True
Starts a kernel process and configures the manager to use it.
def start_kernel(self, **kw): """Starts a kernel process and configures the manager to use it. If random ports (port=0) are being used, this method must be called before the channels are created. Parameters: ----------- launcher : callable, optional (default None) A custom function for launching the kernel process (generally a wrapper around ``entry_point.base_launch_kernel``). In most cases, it should not be necessary to use this parameter. **kw : optional See respective options for IPython and Python kernels. """ if self.ip not in LOCAL_IPS: raise RuntimeError("Can only launch a kernel on a local interface. " "Make sure that the '*_address' attributes are " "configured properly. " "Currently valid addresses are: %s"%LOCAL_IPS ) # write connection file / get default ports self.write_connection_file() self._launch_args = kw.copy() launch_kernel = kw.pop('launcher', None) if launch_kernel is None: from ipkernel import launch_kernel self.kernel = launch_kernel(fname=self.connection_file, **kw)
Attempts to the stop the kernel process cleanly. If the kernel cannot be stopped it is killed if possible.
def shutdown_kernel(self, restart=False): """ Attempts to the stop the kernel process cleanly. If the kernel cannot be stopped, it is killed, if possible. """ # FIXME: Shutdown does not work on Windows due to ZMQ errors! if sys.platform == 'win32': self.kill_kernel() return # Pause the heart beat channel if it exists. if self._hb_channel is not None: self._hb_channel.pause() # Don't send any additional kernel kill messages immediately, to give # the kernel a chance to properly execute shutdown actions. Wait for at # most 1s, checking every 0.1s. self.shell_channel.shutdown(restart=restart) for i in range(10): if self.is_alive: time.sleep(0.1) else: break else: # OK, we've waited long enough. if self.has_kernel: self.kill_kernel() if not restart and self._connection_file_written: # cleanup connection files on full shutdown of kernel we started self._connection_file_written = False try: os.remove(self.connection_file) except IOError: pass
Restarts a kernel with the arguments that were used to launch it.
def restart_kernel(self, now=False, **kw): """Restarts a kernel with the arguments that were used to launch it. If the old kernel was launched with random ports, the same ports will be used for the new kernel. Parameters ---------- now : bool, optional If True, the kernel is forcefully restarted *immediately*, without having a chance to do any cleanup action. Otherwise the kernel is given 1s to clean up before a forceful restart is issued. In all cases the kernel is restarted, the only difference is whether it is given a chance to perform a clean shutdown or not. **kw : optional Any options specified here will replace those used to launch the kernel. """ if self._launch_args is None: raise RuntimeError("Cannot restart the kernel. " "No previous call to 'start_kernel'.") else: # Stop currently running kernel. if self.has_kernel: if now: self.kill_kernel() else: self.shutdown_kernel(restart=True) # Start new kernel. self._launch_args.update(kw) self.start_kernel(**self._launch_args) # FIXME: Messages get dropped in Windows due to probable ZMQ bug # unless there is some delay here. if sys.platform == 'win32': time.sleep(0.2)
Kill the running kernel.
def kill_kernel(self): """ Kill the running kernel. """ if self.has_kernel: # Pause the heart beat channel if it exists. if self._hb_channel is not None: self._hb_channel.pause() # Attempt to kill the kernel. try: self.kernel.kill() except OSError, e: # In Windows, we will get an Access Denied error if the process # has already terminated. Ignore it. if sys.platform == 'win32': if e.winerror != 5: raise # On Unix, we may get an ESRCH error if the process has already # terminated. Ignore it. else: from errno import ESRCH if e.errno != ESRCH: raise self.kernel = None else: raise RuntimeError("Cannot kill kernel. No kernel is running!")
Interrupts the kernel. Unlike signal_kernel this operation is well supported on all platforms.
def interrupt_kernel(self): """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is well supported on all platforms. """ if self.has_kernel: if sys.platform == 'win32': from parentpoller import ParentPollerWindows as Poller Poller.send_interrupt(self.kernel.win32_interrupt_event) else: self.kernel.send_signal(signal.SIGINT) else: raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
Sends a signal to the kernel. Note that since only SIGTERM is supported on Windows this function is only useful on Unix systems.
def signal_kernel(self, signum): """ Sends a signal to the kernel. Note that since only SIGTERM is supported on Windows, this function is only useful on Unix systems. """ if self.has_kernel: self.kernel.send_signal(signum) else: raise RuntimeError("Cannot signal kernel. No kernel is running!")
Is the kernel process still running?
def is_alive(self): """Is the kernel process still running?""" if self.has_kernel: if self.kernel.poll() is None: return True else: return False elif self._hb_channel is not None: # We didn't start the kernel with this KernelManager so we # use the heartbeat. return self._hb_channel.is_beating() else: # no heartbeat and not local, we can't tell if it's running, # so naively return True return True
Get the REQ socket channel object to make requests of the kernel.
def shell_channel(self): """Get the REQ socket channel object to make requests of the kernel.""" if self._shell_channel is None: self._shell_channel = self.shell_channel_class(self.context, self.session, (self.ip, self.shell_port)) return self._shell_channel
Get the SUB socket channel object.
def sub_channel(self): """Get the SUB socket channel object.""" if self._sub_channel is None: self._sub_channel = self.sub_channel_class(self.context, self.session, (self.ip, self.iopub_port)) return self._sub_channel
Get the REP socket channel object to handle stdin ( raw_input ).
def stdin_channel(self): """Get the REP socket channel object to handle stdin (raw_input).""" if self._stdin_channel is None: self._stdin_channel = self.stdin_channel_class(self.context, self.session, (self.ip, self.stdin_port)) return self._stdin_channel
Get the heartbeat socket channel object to check that the kernel is alive.
def hb_channel(self): """Get the heartbeat socket channel object to check that the kernel is alive.""" if self._hb_channel is None: self._hb_channel = self.hb_channel_class(self.context, self.session, (self.ip, self.hb_port)) return self._hb_channel
Bind an Engine s Kernel to be used as a full IPython kernel. This allows a running Engine to be used simultaneously as a full IPython kernel with the QtConsole or other frontends. This function returns immediately.
def bind_kernel(**kwargs): """Bind an Engine's Kernel to be used as a full IPython kernel. This allows a running Engine to be used simultaneously as a full IPython kernel with the QtConsole or other frontends. This function returns immediately. """ from IPython.zmq.ipkernel import IPKernelApp from IPython.parallel.apps.ipengineapp import IPEngineApp # first check for IPKernelApp, in which case this should be a no-op # because there is already a bound kernel if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp): return if IPEngineApp.initialized(): try: app = IPEngineApp.instance() except MultipleInstanceError: pass else: return app.bind_kernel(**kwargs) raise RuntimeError("bind_kernel be called from an IPEngineApp instance")
Emit a debugging message depending on the debugging level.
def debug(self, level, message): """ Emit a debugging message depending on the debugging level. :param level: The debugging level. :param message: The message to emit. """ if self._debug >= level: print(message, file=sys.stderr)
Retrieve the extension classes in priority order.
def _get_extension_classes(cls): """ Retrieve the extension classes in priority order. :returns: A list of extension classes, in proper priority order. """ if cls._extension_classes is None: exts = {} # Iterate over the entrypoints for ext in entry.points[NAMESPACE_EXTENSIONS]: exts.setdefault(ext.priority, []) exts[ext.priority].append(ext) # Save the list of extension classes cls._extension_classes = list(utils.iter_prio_dict(exts)) return cls._extension_classes
Prepare all the extensions. Extensions are prepared during argument parser preparation. An extension implementing the prepare () method is able to add command line arguments specific for that extension.
def prepare(cls, parser): """ Prepare all the extensions. Extensions are prepared during argument parser preparation. An extension implementing the ``prepare()`` method is able to add command line arguments specific for that extension. :param parser: The argument parser, an instance of ``argparse.ArgumentParser``. """ debugger = ExtensionDebugger('prepare') for ext in cls._get_extension_classes(): with debugger(ext): ext.prepare(parser)
Initialize the extensions. This loops over each extension invoking its activate () method ; those extensions that return an object are considered activated and will be called at later phases of extension processing.
def activate(cls, ctxt, args): """ Initialize the extensions. This loops over each extension invoking its ``activate()`` method; those extensions that return an object are considered "activated" and will be called at later phases of extension processing. :param ctxt: An instance of ``timid.context.Context``. :param args: An instance of ``argparse.Namespace`` containing the result of processing command line arguments. :returns: An instance of ``ExtensionSet``. """ debugger = ExtensionDebugger('activate') exts = [] for ext in cls._get_extension_classes(): # Not using debugger as a context manager here, because we # want to know about the exception even if we're ignoring # it...but we need to notify which extension is being # processed! debugger(ext) try: # Check if the extension is being activated obj = ext.activate(ctxt, args) except Exception: # Hmmm, failed to activate; handle the error exc_info = sys.exc_info() if not debugger.__exit__(*exc_info): six.reraise(*exc_info) else: # OK, if the extension is activated, use it if obj is not None: exts.append(obj) debugger.debug(2, 'Activating extension "%s.%s"' % (ext.__module__, ext.__name__)) # Initialize and return the ExtensionSet return cls(exts)
Called after reading steps prior to adding them to the list of test steps. Extensions are able to alter the list ( in place ).
def read_steps(self, ctxt, steps): """ Called after reading steps, prior to adding them to the list of test steps. Extensions are able to alter the list (in place). :param ctxt: An instance of ``timid.context.Context``. :param steps: A list of ``timid.steps.Step`` instances. :returns: The ``steps`` parameter, for convenience. """ debugger = ExtensionDebugger('read_steps') for ext in self.exts: with debugger(ext): ext.read_steps(ctxt, steps) # Convenience return return steps
Called prior to executing a step.
def pre_step(self, ctxt, step, idx): """ Called prior to executing a step. :param ctxt: An instance of ``timid.context.Context``. :param step: An instance of ``timid.steps.Step`` describing the step to be executed. :param idx: The index of the step in the list of steps. :returns: A ``True`` value if the step is to be skipped, ``False`` otherwise. """ debugger = ExtensionDebugger('pre_step') for ext in self.exts: with debugger(ext): if ext.pre_step(ctxt, step, idx): # Step must be skipped debugger.debug(3, 'Skipping step %d' % idx) return True return False
Called after executing a step.
def post_step(self, ctxt, step, idx, result): """ Called after executing a step. :param ctxt: An instance of ``timid.context.Context``. :param step: An instance of ``timid.steps.Step`` describing the step that was executed. :param idx: The index of the step in the list of steps. :param result: An instance of ``timid.steps.StepResult`` describing the result of executing the step. May be altered by the extension, e.g., to set the ``ignore`` attribute. :returns: The ``result`` parameter, for convenience. """ debugger = ExtensionDebugger('post_step') for ext in self.exts: with debugger(ext): ext.post_step(ctxt, step, idx, result) # Convenience return return result
Called at the end of processing. This call allows extensions to emit any additional data such as timing information prior to timid s exit. Extensions may also alter the return value.
def finalize(self, ctxt, result): """ Called at the end of processing. This call allows extensions to emit any additional data, such as timing information, prior to ``timid``'s exit. Extensions may also alter the return value. :param ctxt: An instance of ``timid.context.Context``. :param result: The return value of the basic ``timid`` call, or an ``Exception`` instance if an exception was raised. Without the extension, this would be passed directly to ``sys.exit()``. :returns: The final result. """ debugger = ExtensionDebugger('finalize') for ext in self.exts: with debugger(ext): result = ext.finalize(ctxt, result) return result