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;...
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 ...
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__ ...
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 'forc...
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[ne...
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_fiel...
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, ...
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 ...
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[fulln...
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 == '*': ...
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...
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_reload...
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, ex...
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 ...
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, fil...
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...
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 coun...
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...
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) el...
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) ret...
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() ...
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_t...
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 ...
Activate the default formatters.
def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, SVGFormatter, PNGFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, Javascr...
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 * a...
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 ...
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 ...
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 ...
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. inte...
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...
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. """ ...
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: ...
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...
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: ...
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',N...
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 ...
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 ...
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 No...
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 = '' els...
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...
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 ...
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,**...
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',...
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') ret...
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...
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: ...
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 d...
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(). """ ...
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 =...
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 m...
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): ...
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 ...
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 th...
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....
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, ...
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 com...
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...
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...
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...
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 t...
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. "...
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...
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...
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_cha...
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._...
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'] ...
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....
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) ...
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() ...
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 Tr...
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.kern...
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 Polle...
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 ...
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 KernelMan...
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, ...
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.io...
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, ...
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, ...
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 IPKe...
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 ...
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 parse...
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...
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. ...
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 li...
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 ...
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.Contex...