desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a crash handler, typically setting sys.excepthook to it.'
def init_crash_handler(self):
self.crash_handler = self.crash_handler_class(self) sys.excepthook = self.excepthook def unset_crashhandler(): sys.excepthook = sys.__excepthook__ atexit.register(unset_crashhandler)
'this is sys.excepthook after init_crashhandler set self.verbose_crash=True to use our full crashhandler, instead of a regular traceback with a short message (crash_handler_lite)'
def excepthook(self, etype, evalue, tb):
if self.verbose_crash: return self.crash_handler(etype, evalue, tb) else: return crashhandler.crash_handler_lite(etype, evalue, tb)
'Load the config file. By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail. `supress_errors` default value is to be `None` in which case the behavior default to the one of `traitlets.Application`. The ...
def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
self.log.debug('Searching path %s for config files', self.config_file_paths) base_config = 'ipython_config.py' self.log.debug(('Attempting to load config file: %s' % base_config)) try: if (suppress_errors is not None): old_value = Application.raise_confi...
'initialize the profile dir'
def init_profile_dir(self):
self._in_init_profile_dir = True if (self.profile_dir is not None): return if ('ProfileDir.location' not in self.config): try: p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config) except ProfileDirError: if (self.auto_create or ...
'[optionally] copy default config files into profile dir.'
def init_config_files(self):
self.config_file_paths.extend(ENV_CONFIG_DIRS) self.config_file_paths.extend(SYSTEM_CONFIG_DIRS) path = self.builtin_profile_dir if self.copy_config_files: src = self.profile cfg = self.config_file_name if (path and os.path.exists(os.path.join(path, cfg))): self.log.w...
'auto generate default config file, and stage it into the profile.'
def stage_default_config_file(self):
s = self.generate_config_file() fname = os.path.join(self.profile_dir.location, self.config_file_name) if (self.overwrite or (not os.path.exists(fname))): self.log.warning(('Generating default config file: %r' % fname)) with open(fname, 'w') as f: f.write(s)
'store the macro value, as a single string which can be executed'
def __init__(self, code):
lines = [] enc = None for line in code.splitlines(): coding_match = coding_declaration.match(line) if coding_match: enc = coding_match.group(1) else: lines.append(line) code = '\n'.join(lines) if isinstance(code, bytes): code = code.decode((enc...
'needed for safe pickling via %store'
def __getstate__(self):
return {'value': self.value}
'validate the db, since it can be an Instance of two different types'
@observe('db') def _db_changed(self, change):
new = change['new'] connection_types = (DummyDB,) if (sqlite3 is not None): connection_types = (DummyDB, sqlite3.Connection) if (not isinstance(new, connection_types)): msg = ('%s.db must be sqlite3 Connection or DummyDB, not %r' % (self.__class__.__name__, new)) ...
'Create a new history accessor. Parameters profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~traitlets.config.loader.Config` Config object. hist_file can also be set through...
def __init__(self, profile='default', hist_file=u'', **traits):
super(HistoryAccessor, self).__init__(**traits) if hist_file: self.hist_file = hist_file if (self.hist_file == u''): self.hist_file = self._get_hist_file_name(profile) if ((sqlite3 is None) and self.enabled): warn('IPython History requires SQLite, your history w...
'Find the history file for the given profile name. This is overridden by the HistoryManager subclass, to use the shell\'s active profile. Parameters profile : str The name of a profile which has a history file.'
def _get_hist_file_name(self, profile='default'):
return os.path.join(locate_profile(profile), 'history.sqlite')
'Connect to the database, and create tables if necessary.'
@catch_corrupt_db def init_db(self):
if (not self.enabled): self.db = DummyDB() return kwargs = dict(detect_types=(sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)) kwargs.update(self.connection_options) self.db = sqlite3.connect(self.hist_file, **kwargs) self.db.execute('CREATE TABLE IF NOT EXISTS sessi...
'Overridden by HistoryManager to dump the cache before certain database lookups.'
def writeout_cache(self):
pass
'Prepares and runs an SQL query for the history database. Parameters sql : str Any filtering expressions to go after SELECT ... FROM ... params : tuple Parameters passed to the SQL query (to replace "?") raw, output : bool See :meth:`get_range` Returns Tuples as :meth:`get_range`'
def _run_sql(self, sql, params, raw=True, output=False):
toget = ('source_raw' if raw else 'source') sqlfrom = 'history' if output: sqlfrom = 'history LEFT JOIN output_history USING (session, line)' toget = ('history.%s, output_history.output' % toget) cur = self.db.execute((('SELECT session, line, %s FROM %...
'Get info about a session. Parameters session : int Session number to retrieve. Returns session_id : int Session ID number start : datetime Timestamp for the start of the session. end : datetime Timestamp for the end of the session, or None if IPython crashed. num_cmds : int Number of commands run, or None if IPython c...
@needs_sqlite @catch_corrupt_db def get_session_info(self, session):
query = 'SELECT * from sessions where session == ?' return self.db.execute(query, (session,)).fetchone()
'Get the last session ID currently in the database. Within IPython, this should be the same as the value stored in :attr:`HistoryManager.session_number`.'
@catch_corrupt_db def get_last_session_id(self):
for record in self.get_tail(n=1, include_latest=True): return record[0]
'Get the last n lines from the history database. Parameters n : int The number of lines to get raw, output : bool See :meth:`get_range` include_latest : bool If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it s...
@catch_corrupt_db def get_tail(self, n=10, raw=True, output=False, include_latest=False):
self.writeout_cache() if (not include_latest): n += 1 cur = self._run_sql('ORDER BY session DESC, line DESC LIMIT ?', (n,), raw=raw, output=output) if (not include_latest): return reversed(list(cur)[1:]) return reversed(list(cur))
'Search the database using unix glob-style matching (wildcards * and ?). Parameters pattern : str The wildcarded pattern to match when searching search_raw : bool If True, search the raw input, otherwise, the parsed input raw, output : bool See :meth:`get_range` n : None or int If an integer is given, it defines the li...
@catch_corrupt_db def search(self, pattern='*', raw=True, search_raw=True, output=False, n=None, unique=False):
tosearch = ('source_raw' if search_raw else 'source') if output: tosearch = ('history.' + tosearch) self.writeout_cache() sqlform = ('WHERE %s GLOB ?' % tosearch) params = (pattern,) if unique: sqlform += ' GROUP BY {0}'.format(tosearch) if (n is not None): ...
'Retrieve input by session. Parameters session : int Session number to retrieve. start : int First line to retrieve. stop : int End of line range (excluded from output itself). If None, retrieve to the end of the session. raw : bool If True, return untranslated input output : bool If True, attempt to include output. Th...
@catch_corrupt_db def get_range(self, session, start=1, stop=None, raw=True, output=False):
if stop: lineclause = 'line >= ? AND line < ?' params = (session, start, stop) else: lineclause = 'line>=?' params = (session, start) return self._run_sql(('WHERE session==? AND %s' % lineclause), params, raw=raw, output=output)
'Get lines of history from a string of ranges, as used by magic commands %hist, %save, %macro, etc. Parameters rangestr : str A string specifying ranges, e.g. "5 ~2/1-4". See :func:`magic_history` for full details. raw, output : bool As :meth:`get_range` Returns Tuples as :meth:`get_range`'
def get_range_by_str(self, rangestr, raw=True, output=False):
for (sess, s, e) in extract_hist_ranges(rangestr): for line in self.get_range(sess, s, e, raw=raw, output=output): (yield line)
'Create a new history manager associated with a shell instance.'
def __init__(self, shell=None, config=None, **traits):
super(HistoryManager, self).__init__(shell=shell, config=config, **traits) self.save_flag = threading.Event() self.db_input_cache_lock = threading.Lock() self.db_output_cache_lock = threading.Lock() try: self.new_session() except OperationalError: self.log.error('Failed to ...
'Get default history file name based on the Shell\'s profile. The profile parameter is ignored, but must exist for compatibility with the parent class.'
def _get_hist_file_name(self, profile=None):
profile_dir = self.shell.profile_dir.location return os.path.join(profile_dir, 'history.sqlite')
'Get a new session number.'
@needs_sqlite def new_session(self, conn=None):
if (conn is None): conn = self.db with conn: cur = conn.execute('INSERT INTO sessions VALUES (NULL, ?, NULL,\n NULL, "") ', (datetime.datetime.now(),)) s...
'Close the database session, filling in the end time and line count.'
def end_session(self):
self.writeout_cache() with self.db: self.db.execute('UPDATE sessions SET end=?, num_cmds=? WHERE\n session==?', (datetime.datetime.now(), (len(self.input_hist_parsed) - 1), self....
'Give the current session a name in the history database.'
def name_session(self, name):
with self.db: self.db.execute('UPDATE sessions SET remark=? WHERE session==?', (name, self.session_number))
'Clear the session history, releasing all object references, and optionally open a new session.'
def reset(self, new_session=True):
self.output_hist.clear() self.dir_hist[:] = [os.getcwd()] if new_session: if self.session_number: self.end_session() self.input_hist_parsed[:] = [''] self.input_hist_raw[:] = [''] self.new_session()
'Get info about a session. Parameters session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is the previous session. Returns session_id : int Session ID number start : datetime Timestamp for the start of the session. end : datetime Timestamp for ...
def get_session_info(self, session=0):
if (session <= 0): session += self.session_number return super(HistoryManager, self).get_session_info(session=session)
'Get input and output history from the current session. Called by get_range, and takes similar parameters.'
def _get_range_session(self, start=1, stop=None, raw=True, output=False):
input_hist = (self.input_hist_raw if raw else self.input_hist_parsed) n = len(input_hist) if (start < 0): start += n if ((not stop) or (stop > n)): stop = n elif (stop < 0): stop += n for i in range(start, stop): if output: line = (input_hist[i], self....
'Retrieve input by session. Parameters session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session. start : int First line to retrieve. stop : int End of line range (excluded from output itself). If None, retrieve to the end of the ...
def get_range(self, session=0, start=1, stop=None, raw=True, output=False):
if (session <= 0): session += self.session_number if (session == self.session_number): return self._get_range_session(start, stop, raw, output) return super(HistoryManager, self).get_range(session, start, stop, raw, output)
'Store source and raw input in history and create input cache variables ``_i*``. Parameters line_num : int The prompt number of this input. source : str Python input. source_raw : str, optional If given, this is the raw input without any IPython transformations applied to it. If not given, ``source`` is used.'
def store_inputs(self, line_num, source, source_raw=None):
if (source_raw is None): source_raw = source source = source.rstrip('\n') source_raw = source_raw.rstrip('\n') if self._exit_re.match(source_raw.strip()): return self.input_hist_parsed.append(source) self.input_hist_raw.append(source_raw) with self.db_input_cache_lock: ...
'If database output logging is enabled, this saves all the outputs from the indicated prompt number to the database. It\'s called by run_cell after code has been executed. Parameters line_num : int The line number from which to save outputs'
def store_output(self, line_num):
if ((not self.db_log_output) or (line_num not in self.output_hist_reprs)): return output = self.output_hist_reprs[line_num] with self.db_output_cache_lock: self.db_output_cache.append((line_num, output)) if (self.db_cache_size <= 1): self.save_flag.set()
'Write any entries in the cache to the database.'
@needs_sqlite def writeout_cache(self, conn=None):
if (conn is None): conn = self.db with self.db_input_cache_lock: try: self._writeout_input_cache(conn) except sqlite3.IntegrityError: self.new_session(conn) print ('ERROR! Session/line number was not unique in', 'database. History ...
'This can be called from the main thread to safely stop this thread. Note that it does not attempt to write out remaining history before exiting. That should be done by calling the HistoryManager\'s end_session method.'
def stop(self):
self.stop_now = True self.history_manager.save_flag.set() self.join()
'Generate a new log-file with a default header. Raises RuntimeError if the log has already been started'
def logstart(self, logfname=None, loghead=None, logmode=None, log_output=False, timestamp=False, log_raw_input=False):
if (self.logfile is not None): raise RuntimeError(('Log file is already active: %s' % self.logfname)) if (logfname is not None): self.logfname = logfname if (loghead is not None): self.loghead = loghead if (logmode is not None): self.logmode = logmode s...
'Switch logging on/off. val should be ONLY a boolean.'
def switch_log(self, val):
if (val not in [False, True, 0, 1]): raise ValueError(('Call switch_log ONLY with a boolean argument, not with: %s' % val)) label = {0: 'OFF', 1: 'ON', False: 'OFF', True: 'ON'} if (self.logfile is None): print "\nLogging hasn't been started yet (use...
'Print a status message about the logger.'
def logstate(self):
if (self.logfile is None): print 'Logging has not been activated.' else: state = ((self.log_active and 'active') or 'temporarily suspended') print ('Filename :', self.logfname) print ('Mode :', s...
'Write the sources to a log. Inputs: - line_mod: possibly modified input, such as the transformations made by input prefilters or input handlers of various kinds. This should always be valid Python. - line_ori: unmodified input line from the user. This is not necessarily valid Python.'
def log(self, line_mod, line_ori):
if self.log_raw_input: self.log_write(line_ori) else: self.log_write(line_mod)
'Write data to the log file, if active'
def log_write(self, data, kind='input'):
if (self.log_active and data): write = self.logfile.write if (kind == 'input'): if self.timestamp: write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime())) write(data) elif ((kind == 'output') and self.log_output): ...
'Fully stop logging and close log file. In order to start logging again, a new logstart() call needs to be made, possibly (though not necessarily) with a new filename, mode and other options.'
def logstop(self):
if (self.logfile is not None): self.logfile.close() self.logfile = None else: print "Logging hadn't been started." self.log_active = False
'Do a full, attribute-walking lookup of the ifun in the various namespaces for the given IPython InteractiveShell instance. Return a dict with keys: {found, obj, ospace, ismagic} Note: can cause state changes because of calling getattr, but should only be run if autocall is on and if the line hasn\'t matched any other,...
def ofind(self, ip):
return ip._ofind(self.ifun)
'Create the default transformers.'
def init_transformers(self):
self._transformers = [] for transformer_cls in _default_transformers: transformer_cls(shell=self.shell, prefilter_manager=self, parent=self)
'Sort the transformers by priority. This must be called after the priority of a transformer is changed. The :meth:`register_transformer` method calls this automatically.'
def sort_transformers(self):
self._transformers.sort(key=(lambda x: x.priority))
'Return a list of checkers, sorted by priority.'
@property def transformers(self):
return self._transformers
'Register a transformer instance.'
def register_transformer(self, transformer):
if (transformer not in self._transformers): self._transformers.append(transformer) self.sort_transformers()
'Unregister a transformer instance.'
def unregister_transformer(self, transformer):
if (transformer in self._transformers): self._transformers.remove(transformer)
'Create the default checkers.'
def init_checkers(self):
self._checkers = [] for checker in _default_checkers: checker(shell=self.shell, prefilter_manager=self, parent=self)
'Sort the checkers by priority. This must be called after the priority of a checker is changed. The :meth:`register_checker` method calls this automatically.'
def sort_checkers(self):
self._checkers.sort(key=(lambda x: x.priority))
'Return a list of checkers, sorted by priority.'
@property def checkers(self):
return self._checkers
'Register a checker instance.'
def register_checker(self, checker):
if (checker not in self._checkers): self._checkers.append(checker) self.sort_checkers()
'Unregister a checker instance.'
def unregister_checker(self, checker):
if (checker in self._checkers): self._checkers.remove(checker)
'Create the default handlers.'
def init_handlers(self):
self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler(shell=self.shell, prefilter_manager=self, parent=self)
'Return a dict of all the handlers.'
@property def handlers(self):
return self._handlers
'Register a handler instance by name with esc_strings.'
def register_handler(self, name, handler, esc_strings):
self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
'Unregister a handler instance by name with esc_strings.'
def unregister_handler(self, name, handler, esc_strings):
try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if (h is handler): del self._esc_handlers[esc_str]
'Get a handler by its name.'
def get_handler_by_name(self, name):
return self._handlers.get(name)
'Get a handler by its escape string.'
def get_handler_by_esc(self, esc_str):
return self._esc_handlers.get(esc_str)
'Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe.'
def prefilter_line_info(self, line_info):
handler = self.find_handler(line_info) return handler.handle(line_info)
'Find a handler for the line_info by trying checkers.'
def find_handler(self, line_info):
for checker in self.checkers: if checker.enabled: handler = checker.check(line_info) if handler: return handler return self.get_handler_by_name('normal')
'Calls the enabled transformers in order of increasing priority.'
def transform_line(self, line, continue_prompt):
for transformer in self.transformers: if transformer.enabled: line = transformer.transform(line, continue_prompt) return line
'Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers.'
def prefilter_line(self, line, continue_prompt=False):
self.shell._last_input_line = line if (not line): return '' if ((not continue_prompt) or (continue_prompt and self.multi_line_specials)): line = self.transform_line(line, continue_prompt) line_info = LineInfo(line, continue_prompt) stripped = line.strip() normal_handler = self.ge...
'Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and...
def prefilter_lines(self, lines, continue_prompt=False):
llines = lines.rstrip('\n').split('\n') if (len(llines) > 1): out = '\n'.join([self.prefilter_line(line, (lnum > 0)) for (lnum, line) in enumerate(llines)]) else: out = self.prefilter_line(llines[0], continue_prompt) return out
'Transform a line, returning the new one.'
def transform(self, line, continue_prompt):
return None
'Inspect line_info and return a handler instance or None.'
def check(self, line_info):
return None
'Emacs ipython-mode tags certain input lines.'
def check(self, line_info):
if line_info.line.endswith('# PYTHON-MODE'): return self.prefilter_manager.get_handler_by_name('emacs') else: return None
'Instances of IPyAutocall in user_ns get autocalled immediately'
def check(self, line_info):
obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall): obj.set_ip(self.shell) return self.prefilter_manager.get_handler_by_name('auto') else: return None
'Check to see if user is assigning to a var for the first time, in which case we want to avoid any sort of automagic / autocall games. This allows users to assign to either alias or magic names true python variables (the magic/alias systems always take second seat to true python code). E.g. ls=\'hi\', or ls,that=1,2'
def check(self, line_info):
if line_info.the_rest: if (line_info.the_rest[0] in '=,'): return self.prefilter_manager.get_handler_by_name('normal') else: return None
'If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via \'%\' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.'
def check(self, line_info):
if ((not self.shell.automagic) or (not self.shell.find_magic(line_info.ifun))): return None if (line_info.continue_prompt and (not self.prefilter_manager.multi_line_specials)): return None head = line_info.ifun.split('.', 1)[0] if is_shadowed(head, self.shell): return None re...
'If the \'rest\' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there\'s a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.'
def check(self, line_info):
if (line_info.the_rest and (line_info.the_rest[0] in '!=()<>,+*/%^&|')): return self.prefilter_manager.get_handler_by_name('normal') else: return None
'Check if the initial word/function is callable and autocall is on.'
def check(self, line_info):
if (not self.shell.autocall): return None oinfo = line_info.ofind(self.shell) if (not oinfo['found']): return None ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf'] ifun = line_info.ifun line = line_info.line if ((ifun.lower() in ignored_funs) and (line.startswith((...
'Handle normal input lines. Use as a template for handlers.'
def handle(self, line_info):
line = line_info.line continue_prompt = line_info.continue_prompt if (continue_prompt and self.shell.autoindent and line.isspace() and (0 < abs((len(line) - self.shell.indent_current_nsp)) <= 2)): line = '' return line
'Execute magic functions.'
def handle(self, line_info):
ifun = line_info.ifun the_rest = line_info.the_rest t_arg_s = ((ifun + ' ') + the_rest) (t_magic_name, _, t_magic_arg_s) = t_arg_s.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) cmd = ('%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_ma...
'Handle lines which can be auto-executed, quoting if requested.'
def handle(self, line_info):
line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest esc = line_info.esc continue_prompt = line_info.continue_prompt obj = line_info.ofind(self.shell)['obj'] if continue_prompt: return line force_auto = isinstance(obj, IPyAutocall) try: auto_rewri...
'Handle input lines marked by python-mode.'
def handle(self, line_info):
return line_info.line
'print list of profiles, indented.'
def _print_profiles(self, profiles):
for profile in profiles: print (' %s' % profile)
'import an app class'
def _import_app(self, app_path):
app = None name = app_path.rsplit('.', 1)[(-1)] try: app = import_item(app_path) except ImportError: self.log.info("Couldn't import %s, config file will be excluded", name) except Exception: self.log.warning('Unexpected error importing %s', name,...
'Will be used to set _ip point to current ipython instance b/f call Override this method if you don\'t want this to happen.'
def set_ip(self, ip):
self._ip = ip
'Return true if the given object is defined in the given module.'
def _from_module(self, module, object):
if (module is None): return True elif inspect.isfunction(object): return (module.__dict__ is object.__globals__) elif inspect.isbuiltin(object): return (module.__name__ == object.__module__) elif inspect.isclass(object): return (module.__name__ == object.__module__) e...
'Find tests for the given object and any contained objects, and add them to `tests`.'
def _find(self, tests, obj, name, module, source_lines, globs, seen):
print ('_find for:', obj, name, module) if hasattr(obj, 'skip_doctest'): obj = DocTestSkip(obj) doctest.DocTestFinder._find(self, tests, obj, name, module, source_lines, globs, seen) from inspect import isroutine, isclass if (inspect.ismodule(obj) and self._recurse): for (valname,...
'Check output, accepting special markers embedded in the output. If the output didn\'t pass the default validation but the special string \'#random\' is included, we accept it.'
def check_output(self, want, got, optionflags):
ret = doctest.OutputChecker.check_output(self, want, got, optionflags) if ((not ret) and self.random_re.search(want)): return True return ret
'Modified test setup that syncs with ipython namespace'
def setUp(self):
if isinstance(self._dt_test.examples[0], IPExample): self.user_ns_orig = {} self.user_ns_orig.update(_ip.user_ns) _ip.user_ns.update(self._dt_test.globs) _ip.user_ns.pop('_', None) _ip.user_ns['__builtins__'] = builtin_mod self._dt_test.globs = _ip.user_ns super(D...
'Convert input IPython source into valid Python.'
def ip2py(self, source):
block = _ip.input_transformer_manager.transform_cell(source) if (len(block.splitlines()) == 1): return _ip.prefilter(block) else: return block
'Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages.'
def parse(self, string, name='<string>'):
string = string.expandtabs() min_indent = self._min_indent(string) if (min_indent > 0): string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] (charno, lineno) = (0, 0) if self._RANDOM_TEST.search(string): random_marker = '\n# random' else: ra...
'Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example\'s source code (with prompts and indentation stripped); and `want` is the example\'s expected output (with indentation stripped). `name` is the string\'s name, and `lineno` is the line numbe...
def _parse_example(self, m, name, lineno, ip2py=False):
indent = len(m.group('indent')) source_lines = m.group('source').split('\n') ps1 = m.group('ps1') ps2 = m.group('ps2') ps1_len = len(ps1) self._check_prompt_blank(source_lines, indent, name, lineno, ps1_len) if ps2: self._check_prefix(source_lines[1:], ((' ' * indent) + ps2), name...
'Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. Note: IPython-modified version which takes the input prompt length as a parameter, so that pro...
def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
space_idx = (indent + ps1_len) min_len = (space_idx + 1) for (i, line) in enumerate(lines): if ((len(line) >= min_len) and (line[space_idx] != ' ')): raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), na...
'Look for doctests in the given object, which will be a function, method or class.'
def makeTest(self, obj, parent):
optionflags = (doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS) doctests = self.finder.find(obj, module=getmodule(parent)) if doctests: for test in doctests: if (len(test.examples) == 0): continue (yield DocTestCase(test, obj=obj, optionflags=optionflags, chec...
'Test with only stdout results.'
def test_main_path(self):
self.mktmp("print('A')\nprint('B')\n") out = 'A\nB' tt.ipexec_validate(self.fname, out)
'Test with only stdout results, expecting windows line endings.'
def test_main_path2(self):
self.mktmp("print('A')\nprint('B')\n") out = 'A\r\nB' tt.ipexec_validate(self.fname, out)
'Test exception path in exception_validate.'
def test_exception_path(self):
self.mktmp("import sys\nprint('A')\nprint('B')\nprint('C', file=sys.stderr)\nprint('D', file=sys.stderr)\n") out = 'A\nB' tt.ipexec_validate(self.fname, expected_out=out, expected_err='C\nD')
'Test exception path in exception_validate, expecting windows line endings.'
def test_exception_path2(self):
self.mktmp("import sys\nprint('A')\nprint('B')\nprint('C', file=sys.stderr)\nprint('D', file=sys.stderr)\n") out = 'A\r\nB' tt.ipexec_validate(self.fname, expected_out=out, expected_err='C\r\nD')
'Make a FooClass. Example: >>> f = FooClass(3) junk'
def __init__(self, x):
print 'Making a FooClass.' self.x = x
'Example: >>> ff = FooClass(3) >>> ff.bar(0) boom! >>> 1/0 bam!'
def bar(self, y):
return (1 / y)
'Example: >>> ff2 = FooClass(3) Making a FooClass. >>> ff2.baz(3) True'
def baz(self, y):
return (self.x == y)
'Convert IPython prompts to python ones in a string.'
def __call__(self, ds):
from . import globalipapp pyps1 = '>>> ' pyps2 = '... ' pyout = '' dnew = ds dnew = self.rps1.sub(pyps1, dnew) dnew = self.rps2.sub(pyps2, dnew) dnew = self.rout.sub(pyout, dnew) ip = globalipapp.get_ipython() out = [] newline = out.append for line in dnew.splitline...
'New decorator. Parameters verbose : boolean, optional (False) Passed to the doctest finder and runner to control verbosity.'
def __init__(self, verbose=False):
self.verbose = verbose self.finder = DocTestFinder(verbose=verbose, recurse=False)
'Use as a decorator: doctest a function\'s docstring as a unittest. This version runs normal doctests, but the idea is to make it later run ipython syntax instead.'
def __call__(self, func):
d2u = self if (func.__doc__ is not None): func.__doc__ = ip2py(func.__doc__) class Tester(unittest.TestCase, ): def test(self): runner = DocTestRunner(verbose=d2u.verbose) map(runner.run, d2u.finder.find(func, func.__name__)) failed = count_failures(runner...
'Parameters exclude_patterns : sequence of strings, optional Filenames containing these patterns (as raw strings, not as regular expressions) are excluded from the tests.'
def __init__(self, exclude_patterns=None):
self.exclude_patterns = (exclude_patterns or []) super(ExclusionPlugin, self).__init__()
'Return whether the given filename should be scanned for tests.'
def wantFile(self, filename):
if any(((pat in filename) for pat in self.exclude_patterns)): return False return None
'Return whether the given directory should be scanned for tests.'
def wantDirectory(self, directory):
if any(((pat in directory) for pat in self.exclude_patterns)): return False return None
'Safely stop the thread.'
def halt(self):
if (not self.started): return self.stop.set() os.write(self.writefd, '\x00') self.join()
'Make a valid python temp file.'
def mktmp(self, src, ext='.py'):
(fname, f) = temp_pyfile(src, ext) self.tmpfile = f self.fname = fname