desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'process the input, capturing stdout'
def process_input_line(self, line, store_history=True):
stdout = sys.stdout splitter = self.IP.input_splitter try: sys.stdout = self.cout splitter.push(line) more = splitter.push_accepts_more() if (not more): source_raw = splitter.raw_reset() self.IP.run_cell(source_raw, store_history=store_history) fin...
'# build out an image directive like # .. image:: somefile.png # :width 4in # from an input like # savefig somefile.png width=4in'
def process_image(self, decorator):
savefig_dir = self.savefig_dir source_dir = self.source_dir saveargs = decorator.split(' ') filename = saveargs[1] outfile = ('/' + os.path.relpath(os.path.join(savefig_dir, filename), source_dir)) imagerows = [('.. image:: %s' % outfile)] for kwarg in saveargs[2:]: (arg, va...
'Process data block for INPUT token.'
def process_input(self, data, input_prompt, lineno):
(decorator, input, rest) = data image_file = None image_directive = None is_verbatim = ((decorator == '@verbatim') or self.is_verbatim) is_doctest = (((decorator is not None) and decorator.startswith('@doctest')) or self.is_doctest) is_suppress = ((decorator == '@suppress') or self.is_suppress) ...
'Process data block for OUTPUT token.'
def process_output(self, data, output_prompt, input_lines, output, is_doctest, decorator, image_file):
TAB = (' ' * 4) if (is_doctest and (output is not None)): found = output found = found.strip() submitted = data.strip() if (self.directive is None): source = 'Unavailable' content = 'Unavailable' else: source = self.directive.state.d...
'Process data fPblock for COMMENT token.'
def process_comment(self, data):
if (not self.is_suppress): return [data]
'Saves the image file to disk.'
def save_image(self, image_file):
self.ensure_pyplot() command = ('plt.gcf().savefig("%s")' % image_file) self.process_input_line('bookmark ipy_thisdir', store_history=False) self.process_input_line('cd -b ipy_savedir', store_history=False) self.process_input_line(command, store_history=False) self.process_input_line('c...
'process block from the block_parser and return a list of processed lines'
def process_block(self, block):
ret = [] output = None input_lines = None lineno = self.IP.execution_count input_prompt = (self.promptin % lineno) output_prompt = (self.promptout % lineno) image_file = None image_directive = None found_input = False for (token, data) in block: if (token == COMMENT): ...
'Ensures that pyplot has been imported into the embedded IPython shell. Also, makes sure to set the backend appropriately if not set already.'
def ensure_pyplot(self):
if (not self._pyplot_imported): if ('matplotlib.backends' not in sys.modules): import matplotlib matplotlib.use('agg') self.process_input_line('import matplotlib.pyplot as plt', store_history=False) self._pyplot_imported = True
'content is a list of strings. it is unedited directive content This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code'
def process_pure_python(self, content):
output = [] savefig = False multiline = False multiline_start = None fmtin = self.promptin ct = 0 for (lineno, line) in enumerate(content): line_stripped = line.strip() if (not len(line)): output.append(line) continue if line_stripped.startswit...
'Perform a specialized doctest.'
def custom_doctest(self, decorator, input_lines, found, submitted):
from .custom_doctests import doctests args = decorator.split() doctest_type = args[1] if (doctest_type in doctests): doctests[doctest_type](self, args, input_lines, found, submitted) else: e = 'Invalid option to @doctest: {0}'.format(doctest_type) raise Exception(...
'Reload the raw data from file or URL.'
def reload(self):
import mimetypes if self.embed: super(Audio, self).reload() if (self.filename is not None): self.mimetype = mimetypes.guess_type(self.filename)[0] elif (self.url is not None): self.mimetype = mimetypes.guess_type(self.url)[0] else: self.mimetype = 'audio/wav'
'Transform a numpy array to a PCM bytestring'
def _make_wav(self, data, rate):
import struct from io import BytesIO import wave try: import numpy as np data = np.array(data, dtype=float) if (len(data.shape) == 1): nchan = 1 elif (len(data.shape) == 2): nchan = data.shape[0] data = data.T.ravel() else: ...
'shortcut for returning metadata with url information, if defined'
def _data_and_metadata(self):
md = {} if self.url: md['url'] = self.url if md: return (self.data, md) else: return self.data
'return the embed iframe'
def _repr_html_(self):
if self.params: try: from urllib.parse import urlencode except ImportError: from urllib import urlencode params = ('?' + urlencode(self.params)) else: params = '' return self.iframe.format(src=self.src, width=self.width, height=self.height, params=para...
'Parameters path : str path to the file or directory that should be formatted url_prefix : str prefix to be prepended to all files to form a working link [default: result_html_prefix : str text to append to beginning to link [default: \'\'] result_html_suffix : str text to append at the end of link [default: \'<br>\']'...
def __init__(self, path, url_prefix='', result_html_prefix='', result_html_suffix='<br>'):
if isdir(path): raise ValueError(("Cannot display a directory using FileLink. Use FileLinks to display '%s'." % path)) self.path = path self.url_prefix = url_prefix self.result_html_prefix = result_html_prefix self.result_html_suffix = result_html_suffix
'return html link to file'
def _repr_html_(self):
if (not exists(self.path)): return ("Path (<tt>%s</tt>) doesn't exist. It may still be in the process of being generated, or you may have the incorrect path." % self.path) return self._format_path()
'return absolute path to file'
def __repr__(self):
return abspath(self.path)
'See :class:`FileLink` for the ``path``, ``url_prefix``, ``result_html_prefix`` and ``result_html_suffix`` parameters. included_suffixes : list Filename suffixes to include when formatting output [default: include all files] notebook_display_formatter : function Used to format links for display in the notebook. See dis...
def __init__(self, path, url_prefix='', included_suffixes=None, result_html_prefix='', result_html_suffix='<br>', notebook_display_formatter=None, terminal_display_formatter=None, recursive=True):
if isfile(path): raise ValueError(("Cannot display a file using FileLinks. Use FileLink to display '%s'." % path)) self.included_suffixes = included_suffixes path = path.rstrip('/') self.path = path self.url_prefix = url_prefix self.result_html_prefix = resu...
'generate built-in formatter function this is used to define both the notebook and terminal built-in formatters as they only differ by some wrapper text for each entry dirname_output_format: string to use for formatting directory names, dirname will be substituted for a single "%s" which must appear in this string fnam...
def _get_display_formatter(self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None):
def f(dirname, fnames, included_suffixes=None): result = [] display_fnames = [] for fname in fnames: if (isfile(join(dirname, fname)) and ((included_suffixes is None) or (splitext(fname)[1] in included_suffixes))): display_fnames.append(fname) if (len(disp...
'generate function to use for notebook formatting'
def _get_notebook_display_formatter(self, spacer='&nbsp;&nbsp;'):
dirname_output_format = ((self.result_html_prefix + '%s/') + self.result_html_suffix) fname_output_format = (((self.result_html_prefix + spacer) + self.html_link_str) + self.result_html_suffix) fp_format = (self.url_prefix + '%s/%s') if (sep == '\\'): def fp_cleaner(fp): return fp.re...
'generate function to use for terminal formatting'
def _get_terminal_display_formatter(self, spacer=' '):
dirname_output_format = '%s/' fname_output_format = (spacer + '%s') fp_format = '%s/%s' return self._get_display_formatter(dirname_output_format, fname_output_format, fp_format)
'return newline-separated absolute paths'
def __repr__(self):
result_lines = [] if self.recursive: walked_dir = list(walk(self.path)) else: walked_dir = [next(walk(self.path))] walked_dir.sort() for (dirname, subdirs, fnames) in walked_dir: result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) retu...
'with statement support for indenting/dedenting.'
@contextmanager def indent(self, indent):
self.indentation += indent try: (yield) finally: self.indentation -= indent
'like begin_group / end_group but for the with statement.'
@contextmanager def group(self, indent=0, open='', close=''):
self.begin_group(indent, open) try: (yield) finally: self.end_group(indent, close)
'Add literal text to the output.'
def text(self, obj):
width = len(obj) if self.buffer: text = self.buffer[(-1)] if (not isinstance(text, Text)): text = Text() self.buffer.append(text) text.add(obj, width) self.buffer_width += width self._break_outer_groups() else: self.output.write(obj) ...
'Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space.'
def breakable(self, sep=' '):
width = len(sep) group = self.group_stack[(-1)] if group.want_break: self.flush() self.output.write(self.newline) self.output.write((' ' * self.indentation)) self.output_width = self.indentation self.buffer_width = 0 else: self.buffer.append(Breakable(s...
'Explicitly insert a newline into the output, maintaining correct indentation.'
def break_(self):
self.flush() self.output.write(self.newline) self.output.write((' ' * self.indentation)) self.output_width = self.indentation self.buffer_width = 0
'Begin a group. If you want support for python < 2.5 which doesn\'t has the with statement this is the preferred way: p.begin_group(1, \'{\') p.end_group(1, \'}\') The python 2.5 expression would be this: with p.group(1, \'{\', \'}\'): The first parameter specifies the indentation for the next line (usually the width ...
def begin_group(self, indent=0, open=''):
if open: self.text(open) group = Group((self.group_stack[(-1)].depth + 1)) self.group_stack.append(group) self.group_queue.enq(group) self.indentation += indent
'like enumerate, but with an upper limit on the number of items'
def _enumerate(self, seq):
for (idx, x) in enumerate(seq): if (self.max_seq_length and (idx >= self.max_seq_length)): self.text(',') self.breakable() self.text('...') return (yield (idx, x))
'End a group. See `begin_group` for more details.'
def end_group(self, dedent=0, close=''):
self.indentation -= dedent group = self.group_stack.pop() if (not group.breakables): self.group_queue.remove(group) if close: self.text(close)
'Flush data that is left in the buffer.'
def flush(self):
for data in self.buffer: self.output_width += data.output(self.output, self.output_width) self.buffer.clear() self.buffer_width = 0
'Pretty print the given object.'
def pretty(self, obj):
obj_id = id(obj) cycle = (obj_id in self.stack) self.stack.append(obj_id) self.begin_group() try: obj_class = (_safe_getattr(obj, '__class__', None) or type(obj)) try: printer = self.singleton_pprinters[obj_id] except (TypeError, KeyError): pass ...
'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.'
def _in_deferred_types(self, cls):
mod = _safe_getattr(cls, '__module__', None) name = _safe_getattr(cls, '__name__', None) key = (mod, name) printer = None if (key in self.deferred_pprinters): printer = self.deferred_pprinters.pop(key) self.type_pprinters[cls] = printer return printer
'DEPRECATED since IPython 5.0 Return the current PyOS_InputHook as a ctypes.c_void_p.'
def get_pyos_inputhook(self):
warn('`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) return ctypes.c_void_p.in_dll(ctypes.pythonapi, 'PyOS_InputHook')
'DEPRECATED since IPython 5.0 Return the current PyOS_InputHook as a ctypes.PYFUNCYPE.'
def get_pyos_inputhook_as_func(self):
warn('`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) return self.PYFUNC.in_dll(ctypes.pythonapi, 'PyOS_InputHook')
'DEPRECATED since IPython 5.0 Set PyOS_InputHook to callback and return the previous one.'
def set_inputhook(self, callback):
ignore_CTRL_C() self._callback = callback self._callback_pyfunctype = self.PYFUNC(callback) pyos_inputhook_ptr = self.get_pyos_inputhook() original = self.get_pyos_inputhook_as_func() pyos_inputhook_ptr.value = ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value self._installed = T...
'DEPRECATED since IPython 5.0 Set PyOS_InputHook to NULL and return the previous one. Parameters app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` methods. But the actual value of the parameter is ignored. This uniform inter...
def clear_inputhook(self, app=None):
warn('`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) pyos_inputhook_ptr = self.get_pyos_inputhook() original = self.get_pyos_inputhook_as_func() pyos_inputhook_ptr.value = ctypes.c_void_p(N...
'DEPRECATED since IPython 5.0 Clear IPython\'s internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn\'t hold a reference themselves. This method is provided to clear t...
def clear_app_refs(self, gui=None):
warn('`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) if (gui is None): self.apps = {} elif (gui in self.apps): del self.apps[gui]
'DEPRECATED since IPython 5.0 Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass :class:`InputHookBase`. @inputhook_manager.register(\'qt\') class ...
def register(self, toolkitname, *aliases):
warn('`register` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) def decorator(cls): if (ctypes is not None): inst = cls(self) self.guihooks[toolkitname] = inst for a in al...
'DEPRECATED since IPython 5.0 Return a string indicating the currently active GUI or None.'
def current_gui(self):
warn('`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) return self._current_gui
'DEPRECATED since IPython 5.0 Switch amongst GUI input hooks by name. This is a higher level method than :meth:`set_inputhook` - it uses the GUI name to look up a registered object which enables the input hook for that GUI. Parameters gui : optional, string or None If None (or \'none\'), clears input hook, otherwise it...
def enable_gui(self, gui=None, app=None):
warn('`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) if (gui in (None, GUI_NONE)): return self.disable_gui() if (gui in self.aliases): return self.enable_gui(self.aliases[gui], app) ...
'DEPRECATED since IPython 5.0 Disable GUI event loop integration. If an application was registered, this sets its ``_in_event_loop`` attribute to False. It then calls :meth:`clear_inputhook`.'
def disable_gui(self):
warn('`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) gui = self._current_gui if (gui in self.apps): self.apps[gui]._in_event_loop = False return self.clear_inputhook()
'DEPRECATED since IPython 5.0 Enable event loop integration with wxPython. Parameters app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. Notes This methods sets the ``PyOS_InputHook`` for wxPython, which allow...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) import wx wx_version = V(wx.__version__).version if (wx_version < [2, 8]): raise ValueError(('requires wxPython >= 2.8, ...
'DEPRECATED since IPython 5.0 Disable event loop integration with wxPython. This restores appnapp on OS X'
def disable(self):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) if _use_appnope(): from appnope import nap nap()
'DEPRECATED since IPython 5.0 Enable event loop integration with PyQt4. Parameters app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Notes This methods sets the PyOS_InputHook for PyQt4, which allows the PyQt...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) from IPython.lib.inputhookqt4 import create_inputhook_qt4 (app, inputhook_qt4) = create_inputhook_qt4(self.manager, app) self.manager.set...
'DEPRECATED since IPython 5.0 Disable event loop integration with PyQt4. This restores appnapp on OS X'
def disable_qt4(self):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) if _use_appnope(): from appnope import nap nap()
'DEPRECATED since IPython 5.0 Enable event loop integration with PyGTK. Parameters app : ignored Ignored, it\'s only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes This methods sets the PyOS_InputHook for PyGTK, which allows the ...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) import gtk try: gtk.set_interactive(True) except AttributeError: from IPython.lib.inputhookgtk import inputhook_gtk ...
'DEPRECATED since IPython 5.0 Enable event loop integration with Tk. Parameters app : toplevel :class:`Tkinter.Tk` widget, optional. Running toplevel widget to use. If not given, we probe Tk for an existing one, and create a new one if none is found. Notes If you have already created a :class:`Tkinter.Tk` object, the ...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) if (app is None): try: from tkinter import Tk except ImportError: from Tkinter import Tk app = Tk...
'DEPRECATED since IPython 5.0 Enable event loop integration with GLUT. Parameters app : ignored Ignored, it\'s only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes This methods sets the PyOS_InputHook for GLUT, which allows the GL...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) import OpenGL.GLUT as glut from IPython.lib.inputhookglut import glut_display_mode, glut_close, glut_display, glut_idle, inputhook_glut i...
'DEPRECATED since IPython 5.0 Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future.'
def disable(self):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) import OpenGL.GLUT as glut from glut_support import glutMainLoopEvent glut.glutHideWindow() glutMainLoopEvent() super(GlutInputHo...
'DEPRECATED since IPython 5.0 Enable event loop integration with pyglet. Parameters app : ignored Ignored, it\'s only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes This methods sets the ``PyOS_InputHook`` for pyglet, which allow...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) from IPython.lib.inputhookpyglet import inputhook_pyglet self.manager.set_inputhook(inputhook_pyglet) return app
'DEPRECATED since IPython 5.0 Enable event loop integration with Gtk3 (gir bindings). Parameters app : ignored Ignored, it\'s only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes This methods sets the PyOS_InputHook for Gtk3, whic...
def enable(self, app=None):
warn('This function is deprecated since IPython 5.0 and will be removed in future versions.', DeprecationWarning, stacklevel=2) from IPython.lib.inputhookgtk3 import inputhook_gtk3 self.manager.set_inputhook(inputhook_gtk3)
'Add a new background job and start it in a separate thread. There are two types of jobs which can be created: 1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example: job_manager.new(\'myfunc(x,y,z=1)\'[,glob[,loc]]) The given expression is passed to e...
def new(self, func_or_exp, *args, **kwargs):
if callable(func_or_exp): kw = kwargs.get('kw', {}) job = BackgroundJobFunc(func_or_exp, *args, **kw) elif isinstance(func_or_exp, str): if (not args): frame = sys._getframe(1) (glob, loc) = (frame.f_globals, frame.f_locals) elif (len(args) == 1): ...
'An alias to self.status(), This allows you to simply call a job manager instance much like the Unix `jobs` shell command.'
def __call__(self):
return self.status()
'Update the status of the job lists. This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died. It also copies those jobs to corresponding _report lists. These lists are used to report jobs completed/dead since the last update, an...
def _update_status(self):
(srun, scomp, sdead) = (self._s_running, self._s_completed, self._s_dead) (running, completed, dead) = (self._running, self._completed, self._dead) for (num, job) in enumerate(running): stat = job.stat_code if (stat == srun): continue elif (stat == scomp): com...
'Report summary for a given job group. Return True if the group had any elements.'
def _group_report(self, group, name):
if group: print ('%s jobs:' % name) for job in group: print ('%s : %s' % (job.num, job)) print () return True
'Flush a given job group Return True if the group had any elements.'
def _group_flush(self, group, name):
njobs = len(group) if njobs: plural = {1: ''}.setdefault(njobs, 's') print ('Flushing %s %s job%s.' % (njobs, name, plural)) group[:] = [] return True
'Print the status of newly finished jobs. Return True if any new jobs are reported. This call resets its own state every time, so it only reports jobs which have finished since the last time it was called.'
def _status_new(self):
self._update_status() new_comp = self._group_report(self._comp_report, 'Completed') new_dead = self._group_report(self._dead_report, 'Dead, call jobs.traceback() for details') self._comp_report[:] = [] self._dead_report[:] = [] return (new_comp or new_dead)
'Print a status of all jobs currently being managed.'
def status(self, verbose=0):
self._update_status() self._group_report(self.running, 'Running') self._group_report(self.completed, 'Completed') self._group_report(self.dead, 'Dead') self._comp_report[:] = [] self._dead_report[:] = []
'Remove a finished (completed or dead) job.'
def remove(self, num):
try: job = self.all[num] except KeyError: error(('Job #%s not found' % num)) else: stat_code = job.stat_code if (stat_code == self._s_running): error(('Job #%s is still running, it can not be removed.' % num)) return...
'Flush all finished jobs (completed and dead) from lists. Running jobs are never flushed. It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts.'
def flush(self):
alljobs = self.all for job in (self.completed + self.dead): del alljobs[job.num] fl_comp = self._group_flush(self.completed, 'Completed') fl_dead = self._group_flush(self.dead, 'Dead') if (not (fl_comp or fl_dead)): print 'No jobs to flush.'
'result(N) -> return the result of job N.'
def result(self, num):
try: return self.all[num].result except KeyError: error(('Job #%s not found' % num))
'Must be implemented in subclasses. Subclasses must call :meth:`_init` for standard initialisation.'
def __init__(self):
raise NotImplementedError('This class can not be instantiated directly.')
'Common initialization for all BackgroundJob objects'
def _init(self):
for attr in ['call', 'strform']: assert hasattr(self, attr), ('Missing attribute <%s>' % attr) self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not complet...
'Create a new job from a string which can be fed to eval(). global/locals dicts can be provided, which will be passed to the eval call.'
def __init__(self, expression, glob=None, loc=None):
self.code = compile(expression, '<BackgroundJob compilation>', 'eval') glob = ({} if (glob is None) else glob) loc = ({} if (loc is None) else loc) self.expression = self.strform = expression self.glob = glob self.loc = loc self._init()
'Create a new job from a callable object. Any positional arguments and keyword args given to this constructor after the initial callable are passed directly to it.'
def __init__(self, func, *args, **kwargs):
if (not callable(func)): raise TypeError('first argument to BackgroundJobFunc must be callable') self.func = func self.args = args self.kwargs = kwargs self.strform = str(func) self._init()
'Initialize the IPython console lexer. Parameters python3 : bool If `True`, then the console inputs are parsed using a Python 3 lexer. Otherwise, they are parsed using a Python 2 lexer. in1_regex : RegexObject The compiled regular expression used to detect the start of inputs. Although the IPython configuration setting...
def __init__(self, **options):
self.python3 = get_bool_opt(options, 'python3', False) if self.python3: self.aliases = ['ipython3console'] else: self.aliases = ['ipython2console', 'ipythonconsole'] in1_regex = options.get('in1_regex', self.in1_regex) in2_regex = options.get('in2_regex', self.in2_regex) out_rege...
'Generator of unprocessed tokens after doing insertions and before changing to a new state.'
def buffered_tokens(self):
if (self.mode == 'output'): tokens = [(0, Generic.Output, self.buffer)] elif (self.mode == 'input'): tokens = self.pylexer.get_tokens_unprocessed(self.buffer) else: tokens = self.tblexer.get_tokens_unprocessed(self.buffer) for (i, t, v) in do_insertions(self.insertions, tokens): ...
'Parses the line and returns a 3-tuple: (mode, code, insertion). `mode` is the next mode (or state) of the lexer, and is always equal to \'input\', \'output\', or \'tb\'. `code` is a portion of the line that should be added to the buffer corresponding to the next mode and eventually lexed by another lexer. For example,...
def get_mci(self, line):
in2_match = self.in2_regex.match(line) in2_match_rstrip = self.in2_regex_rstrip.match(line) if ((in2_match and (in2_match.group().rstrip() == line.rstrip())) or in2_match_rstrip): end_input = True else: end_input = False if (end_input and (self.mode != 'tb')): mode = 'output'...
'Write a file, and force a timestamp difference of at least one second Notes Python\'s .pyc files record the timestamp of their compilation with a time resolution of one second. Therefore, we need to force a timestamp difference between .py and .pyc, without having the .py file be timestamped in the future, and without...
def write_file(self, filename, content):
time.sleep(1.05) f = open(filename, 'w') try: f.write(content) finally: f.close()
'Functional test for the automatic reloader using either \'%autoreload 1\' or \'%autoreload 2\''
def _check_smoketest(self, use_aimport=True):
(mod_name, mod_fn) = self.new_module("\nx = 9\n\nz = 123 # this item will be deleted\n\ndef foo(y):\n return y + 3\n\nclass Baz(object):\n def __init__(self, x):\n self.x = x\n de...
'Lightweight persistence for python variables. Example:: In [1]: l = [\'hello\',10,\'world\'] In [2]: %store l In [3]: exit (IPython session is closed and started again...) ville@badger:~$ ipython In [1]: l NameError: name \'l\' is not defined In [2]: %store -r In [3]: l Out[3]: [\'hello\', 10, \'world\'] Usage: * ``%s...
@line_magic def store(self, parameter_s=''):
(opts, argsl) = self.parse_options(parameter_s, 'drz', mode='string') args = argsl.split(None, 1) ip = self.shell db = ip.db if ('d' in opts): try: todel = args[0] except IndexError: raise UsageError('You must provide the variable to forget')...
'get the name of the mirrored module'
def _mirror_name(self, fullname):
return (self.mirror + fullname[len(self.src):])
'Return self if we should be used to import the module.'
def find_module(self, fullname, path=None):
if fullname.startswith((self.src + '.')): mirror_name = self._mirror_name(fullname) try: mod = import_item(mirror_name) except ImportError: return else: if (not isinstance(mod, types.ModuleType)): return None return self...
'Import the mirrored module, and insert it into sys.modules'
def load_module(self, fullname):
mirror_name = self._mirror_name(fullname) mod = import_item(mirror_name) sys.modules[fullname] = mod return mod
'Don\'t produce __spec__ until requested'
@property def __spec__(self):
return import_module(self._mirror).__spec__
'Ensure __all__ is always defined'
@property def __all__(self):
mod = import_module(self._mirror) try: return mod.__all__ except AttributeError: return [name for name in dir(mod) if (not name.startswith('_'))]
'Captured standard output'
@property def stdout(self):
if (not self._stdout): return '' return self._stdout.getvalue()
'Captured standard error'
@property def stderr(self):
if (not self._stderr): return '' return self._stderr.getvalue()
'A list of the captured rich display outputs, if any. If you have a CapturedIO object ``c``, these can be displayed in IPython using:: from IPython.display import display for o in c.outputs: display(o)'
@property def outputs(self):
return [RichOutput(d, md) for (d, md) in self._outputs]
'write my output to sys.stdout/err as appropriate'
def show(self):
sys.stdout.write(self.stdout) sys.stderr.write(self.stderr) sys.stdout.flush() sys.stderr.flush() for (data, metadata) in self._outputs: RichOutput(data, metadata).display()
'Adds a target \'string\' for dispatching'
def add_s(self, s, obj, priority=0):
chain = self.strs.get(s, CommandChainDispatcher()) chain.add(obj, priority) self.strs[s] = chain
'Adds a target regexp for dispatching'
def add_re(self, regex, obj, priority=0):
chain = self.regexs.get(regex, CommandChainDispatcher()) chain.add(obj, priority) self.regexs[regex] = chain
'Get a seq of Commandchain objects that match key'
def dispatch(self, key):
if (key in self.strs): (yield self.strs[key]) for (r, obj) in self.regexs.items(): if re.match(r, key): (yield obj) else: pass
'Yield all \'value\' targets, without priority'
def flat_matches(self, key):
for val in self.dispatch(key): for el in val: (yield el[1]) return
'Dictionaries should be indexed by attributes, not by keys. This was causing Github issue 129.'
def test_dict_attributes(self):
ns = {'az': {'king': 55}, 'pq': {1: 0}} tests = [('a*', ['az']), ('az.k*', ['az.keys']), ('pq.k*', ['pq.keys'])] for (pat, res) in tests: res.sort() a = sorted(wildcard.list_namespace(ns, 'all', pat, ignore_case=False, show_all=True).keys()) self.assertEqual(a, res)
'Make a valid python temp file.'
def setUp(self):
lines = ['import sys', "print('on stdout', end='', file=sys.stdout)", "print('on stderr', end='', file=sys.stderr)", 'sys.stdout.flush()', 'sys.stderr.flush()'] self.mktmp('\n'.join(lines))
'Return all strings matching \'pattern\' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( lambda x: x.startswith(\'C\') ) a.grep(\'Cha.*log\', prune=1) ...
def grep(self, pattern, prune=False, field=None):
def match_target(s): if (field is None): return s parts = s.split() try: tgt = parts[field] return tgt except IndexError: return '' if isinstance(pattern, str): pred = (lambda x: re.search(pattern, x, re.IGNORECASE)) els...
'Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by \'a = !ls -l\'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython * ``a.fields(0)`` is ``[\'-rwxrwxrwx\', \'drwxrwxrwx+\']``...
def fields(self, *fields):
if (len(fields) == 0): return [el.split() for el in self] res = SList() for el in [f.split() for f in self]: lineparts = [] for fd in fields: try: lineparts.append(el[fd]) except IndexError: pass if lineparts: ...
'sort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3)'
def sort(self, field=None, nums=False):
if (field is not None): dsu = [[SList([line]).fields(field), line] for line in self] else: dsu = [[line, line] for line in self] if nums: for i in range(len(dsu)): numstr = ''.join([ch for ch in dsu[i][0] if ch.isdigit()]) try: n = int(numstr) ...
'Return a full copy of the object, optionally renaming it.'
def copy(self, name=None):
if (name is None): name = self.name return ColorScheme(name, self.colors.dict())
'Create a table of color schemes. The table can be created empty and manually filled or it can be created with a list of valid color schemes AND the specification for the default active scheme.'
def __init__(self, scheme_list=None, default_scheme=''):
self.active_scheme_name = '' self.active_colors = None if scheme_list: if (default_scheme == ''): raise ValueError('you must specify the default color scheme') for scheme in scheme_list: self.add_scheme(scheme) self.set_active_scheme(default_...
'Return full copy of object'
def copy(self):
return ColorSchemeTable(self.values(), self.active_scheme_name)
'Add a new color scheme to the table.'
def add_scheme(self, new_scheme):
if (not isinstance(new_scheme, ColorScheme)): raise ValueError('ColorSchemeTable only accepts ColorScheme instances') self[new_scheme.name] = new_scheme
'Set the currently active scheme. Names are by default compared in a case-insensitive way, but this can be changed by setting the parameter case_sensitive to true.'
def set_active_scheme(self, scheme, case_sensitive=0):
scheme_names = list(self.keys()) if case_sensitive: valid_schemes = scheme_names scheme_test = scheme else: valid_schemes = [s.lower() for s in scheme_names] scheme_test = scheme.lower() try: scheme_idx = valid_schemes.index(scheme_test) except ValueError: ...
'Create a parser with a specified color table and output channel. Call format() to process code.'
def __init__(self, color_table=None, out=sys.stdout, parent=None, style=None):
super(Parser, self).__init__(parent=parent) self.color_table = ((color_table and color_table) or ANSICodeColors) self.out = out if (not style): self.style = self.default_style else: self.style = style
'Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string \'str\' and the parser will automatically return the output in a string.'
def format2(self, raw, out=None):
string_output = 0 if ((out == 'str') or (self.out == 'str') or isinstance(self.out, StringIO)): out_old = self.out self.out = StringIO() string_output = 1 elif (out is not None): self.out = out if (self.style == 'NoColor'): error = False self.out.write(raw...
'Token handler, with syntax highlighting.'
def __call__(self, toktype, toktext, start_pos, end_pos, line):
(srow, scol) = start_pos (erow, ecol) = end_pos colors = self.colors owrite = self.out.write linesep = os.linesep oldpos = self.pos newpos = (self.lines[srow] + scol) self.pos = (newpos + len(toktext)) if (newpos > oldpos): owrite(self.raw[oldpos:newpos]) if (toktype in [...
'Open a file named `filename` in a temporary directory. This context manager is preferred over `NamedTemporaryFile` in stdlib `tempfile` when one needs to reopen the file. Arguments `mode` and `bufsize` are passed to `open`. Rest of the arguments are passed to `TemporaryDirectory`.'
def __init__(self, filename, mode='w+b', bufsize=(-1), **kwds):
self._tmpdir = TemporaryDirectory(**kwds) path = _os.path.join(self._tmpdir.name, filename) self.file = open(path, mode, bufsize)
'Initialize with a dictionary, another Struct, or data. Parameters args : dict, Struct Initialize with one dict or Struct kw : dict Initialize with key, value pairs. Examples >>> s = Struct(a=10,b=30) >>> s.a 10 >>> s.b 30 >>> s2 = Struct(s,c=30) >>> sorted(s2.keys()) [\'a\', \'b\', \'c\']'
def __init__(self, *args, **kw):
object.__setattr__(self, '_allownew', True) dict.__init__(self, *args, **kw)