INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Register a function for calling after code execution. | def register_post_execute(self, func):
"""Register a function for calling after code execution.
"""
if not callable(func):
raise ValueError('argument %s must be callable' % func)
self._post_execute[func] = True |
Return a new main module object for user code execution. | def new_main_mod(self,ns=None):
"""Return a new 'main' module object for user code execution.
"""
main_mod = self._user_main_module
init_fakemod_dict(main_mod,ns)
return main_mod |
Cache a main module s namespace. | def cache_main_mod(self,ns,fname):
"""Cache a main module's namespace.
When scripts are executed via %run, we must keep a reference to the
namespace of their __main__ module (a FakeModule instance) around so
that Python doesn't clear it, rendering objects defined therein
useless... |
Call the pydb/ pdb debugger. | def debugger(self,force=False):
"""Call the pydb/pdb debugger.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if t... |
Prepare the module and namespace in which user code will be run. When IPython is started normally both parameters are None: a new module is created automatically and its __dict__ used as the namespace. If only user_module is provided its __dict__ is used as the namespace. If only user_ns is provided a dummy module is c... | def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
... |
Initialize all user - visible namespaces to their minimum defaults. | def init_user_ns(self):
"""Initialize all user-visible namespaces to their minimum defaults.
Certain history lists are also initialized here, as they effectively
act as user namespaces.
Notes
-----
All data structures here are only filled in, they are NOT reset by this
... |
Get a list of references to all the namespace dictionaries in which IPython might store a user - created object. Note that this does not include the displayhook which also caches objects from the output. | def all_ns_refs(self):
"""Get a list of references to all the namespace dictionaries in which
IPython might store a user-created object.
Note that this does not include the displayhook, which also caches
objects from the output."""
return [self.user_ns, self.user_global_... |
Clear all internal namespaces and attempt to release references to user objects. | def reset(self, new_session=True):
"""Clear all internal namespaces, and attempt to release references to
user objects.
If new_session is True, a new history session will be opened.
"""
# Clear histories
self.history_manager.reset(new_session)
# Reset counter use... |
Delete a variable from the various namespaces so that as far as possible we re not keeping any hidden references to it. | def del_var(self, varname, by_name=False):
"""Delete a variable from the various namespaces, so that, as
far as possible, we're not keeping any hidden references to it.
Parameters
----------
varname : str
The name of the variable to delete.
by_name : bool
... |
Clear selective variables from internal namespaces based on a specified regular expression. | def reset_selective(self, regex=None):
"""Clear selective variables from internal namespaces based on a
specified regular expression.
Parameters
----------
regex : string or compiled pattern, optional
A regular expression pattern that will be used in searching
... |
Inject a group of variables into the IPython user namespace. | def push(self, variables, interactive=True):
"""Inject a group of variables into the IPython user namespace.
Parameters
----------
variables : dict, str or list/tuple of str
The variables to inject into the user's namespace. If a dict, a
simple update is done. ... |
Remove a dict of variables from the user namespace if they are the same as the values in the dictionary. This is intended for use by extensions: variables that they ve added can be taken back out if they are unloaded without removing any that the user has overwritten. Parameters ---------- variables: dict A dictionary ... | def drop_by_id(self, variables):
"""Remove a dict of variables from the user namespace, if they are the
same as the values in the dictionary.
This is intended for use by extensions: variables that they've added can
be taken back out if they are unloaded, without removing any tha... |
Find an object in the available namespaces. | def _ofind(self, oname, namespaces=None):
"""Find an object in the available namespaces.
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
Has special code to detect magic functions.
"""
oname = oname.strip()
#print '1- oname: <%r>' % oname # dbg
i... |
Second part of object finding to look for property details. | def _ofind_property(self, oname, info):
"""Second part of object finding, to look for property details."""
if info.found:
# Get the docstring of the class property if it exists.
path = oname.split('.')
root = '.'.join(path[:-1])
if info.parent is not None:... |
Find an object and return a struct with info about it. | def _object_find(self, oname, namespaces=None):
"""Find an object and return a struct with info about it."""
inf = Struct(self._ofind(oname, namespaces))
return Struct(self._ofind_property(oname, inf)) |
Generic interface to the inspector system. | def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
This function is meant to be called by pdef, pdoc & friends."""
info = self._object_find(oname, namespaces)
if info.found:
pmethod = getattr(self.inspector, meth)
... |
Sets up the command history and starts regular autosaves. | def init_history(self):
"""Sets up the command history, and starts regular autosaves."""
self.history_manager = HistoryManager(shell=self, config=self.config)
self.configurables.append(self.history_manager) |
set_custom_exc ( exc_tuple handler ) | def set_custom_exc(self, exc_tuple, handler):
"""set_custom_exc(exc_tuple,handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
run_code() method).
Parameters
----------
e... |
One more defense for GUI apps that call sys. excepthook. | def excepthook(self, etype, value, tb):
"""One more defense for GUI apps that call sys.excepthook.
GUI frameworks like wxPython trap exceptions and call
sys.excepthook themselves. I guess this is a feature that
enables them to keep running after exceptions that would
otherwise kill their... |
get exc_info from a given tuple sys. exc_info () or sys. last_type etc. Ensures sys. last_type value traceback hold the exc_info we found from whichever source. raises ValueError if none of these contain any information | def _get_exc_info(self, exc_tuple=None):
"""get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
raises ValueError if none of these contain any information
... |
Display the exception that just occurred. | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
exception_only=False):
"""Display the exception that just occurred.
If nothing is known about the exception, this is the method which
should be used throughout the code for presenting user tracebacks,
... |
Actually show a traceback. | def _showtraceback(self, etype, evalue, stb):
"""Actually show a traceback.
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
print >> io.stdout, self.InteractiveTB.stb2text(stb) |
Display the syntax error that just occurred. | def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
This doesn't display a stack trace because there isn't one.
If a filename is given, it is stuffed in the exception instead
of what was there before (because Python's parser always uses
"<s... |
Command history completion/ saving/ reloading. | def init_readline(self):
"""Command history completion/saving/reloading."""
if self.readline_use:
import IPython.utils.rlineimpl as readline
self.rl_next_input = None
self.rl_do_indent = False
if not self.readline_use or not readline.have_readline:
self... |
readline hook to be used at the start of each line. | def pre_readline(self):
"""readline hook to be used at the start of each line.
Currently it handles auto-indent only."""
if self.rl_do_indent:
self.readline.insert_text(self._indent_current_str())
if self.rl_next_input is not None:
self.readline.insert_text(self... |
Initialize the completion machinery. | def init_completer(self):
"""Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programatically (such as in test suites) or out-of-prcess
(typicall... |
Return the completed text and a list of completions. | def complete(self, text, line=None, cursor_pos=None):
"""Return the completed text and a list of completions.
Parameters
----------
text : string
A string of text to be completed on. It can be given as empty and
instead a line/position pair are given. In ... |
Adds a new custom completer function. | def set_custom_completer(self, completer, pos=0):
"""Adds a new custom completer function.
The position argument (defaults to 0) is the index in the completers
list where you want the completer to be inserted."""
newcomp = types.MethodType(completer,self.Completer)
self.Complet... |
Set the frame of the completer. | def set_completer_frame(self, frame=None):
"""Set the frame of the completer."""
if frame:
self.Completer.namespace = frame.f_locals
self.Completer.global_namespace = frame.f_globals
else:
self.Completer.namespace = self.user_ns
self.Completer.glob... |
Execute the given line magic. | def run_line_magic(self, magic_name, line):
"""Execute the given line magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the input line as a single string.
"""
fn = sel... |
Execute the given cell magic. Parameters ---------- magic_name: str Name of the desired magic function without % prefix. | def run_cell_magic(self, magic_name, line, cell):
"""Execute the given cell magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the first input line as a single string.
... |
Find and return a magic of the given type by name. | def find_magic(self, magic_name, magic_kind='line'):
"""Find and return a magic of the given type by name.
Returns None if the magic isn't found."""
return self.magics_manager.magics[magic_kind].get(magic_name) |
DEPRECATED. Use run_line_magic () instead. | def magic(self, arg_s):
"""DEPRECATED. Use run_line_magic() instead.
Call a magic function by name.
Input: a string containing the name of the magic function to call and
any additional arguments to be passed to the magic.
magic('name -opt foo bar') is equivalent to typing at t... |
Define a new macro | def define_macro(self, name, themacro):
"""Define a new macro
Parameters
----------
name : str
The name of the macro.
themacro : str or Macro
The action to do upon invoking the macro. If a string, a new
Macro object is created by passing the ... |
Call the given cmd in a subprocess using os. system | def system_raw(self, cmd):
"""Call the given cmd in a subprocess using os.system
Parameters
----------
cmd : str
Command to execute.
"""
cmd = self.var_expand(cmd, depth=1)
# protect os.system from UNC paths on Windows, which it can't handle:
if... |
Get output ( possibly including stderr ) from a subprocess. | def getoutput(self, cmd, split=True, depth=0):
"""Get output (possibly including stderr) from a subprocess.
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported.
split : bool, optional
If ... |
Print to the screen the rewritten form of the user s command. | def auto_rewrite_input(self, cmd):
"""Print to the screen the rewritten form of the user's command.
This shows visual feedback by rewriting input lines that cause
automatic calling to kick in, like::
/f x
into::
------> f(x)
after the user's input prompt.... |
Get a list of variable names from the user s namespace. | def user_variables(self, names):
"""Get a list of variable names from the user's namespace.
Parameters
----------
names : list of strings
A list of names of variables to be read from the user namespace.
Returns
-------
A dict, keyed by the input names ... |
Evaluate a dict of expressions in the user s namespace. | def user_expressions(self, expressions):
"""Evaluate a dict of expressions in the user's namespace.
Parameters
----------
expressions : dict
A dict with string keys and string values. The expression values
should be valid Python expressions, each of which will be ev... |
Execute a normal python statement in user namespace. | def ex(self, cmd):
"""Execute a normal python statement in user namespace."""
with self.builtin_trap:
exec cmd in self.user_global_ns, self.user_ns |
Evaluate python expression expr in user namespace. | def ev(self, expr):
"""Evaluate python expression expr in user namespace.
Returns the result of evaluation
"""
with self.builtin_trap:
return eval(expr, self.user_global_ns, self.user_ns) |
A safe version of the builtin execfile (). | def safe_execfile(self, fname, *where, **kw):
"""A safe version of the builtin execfile().
This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Parameters
------... |
Like safe_execfile but for. ipy files with IPython syntax. | def safe_execfile_ipy(self, fname):
"""Like safe_execfile, but for .ipy files with IPython syntax.
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
.ipy extension.
"""
fname = os.path.abspath(os.path.exp... |
A safe version of runpy. run_module (). | def safe_run_module(self, mod_name, where):
"""A safe version of runpy.run_module().
This version will never throw an exception, but instead print
helpful error messages to the screen.
Parameters
----------
mod_name : string
The name of the module to be exec... |
Special method to call a cell magic with the data stored in self. | def _run_cached_cell_magic(self, magic_name, line):
"""Special method to call a cell magic with the data stored in self.
"""
cell = self._current_cell_magic_body
self._current_cell_magic_body = None
return self.run_cell_magic(magic_name, line, cell) |
Run a complete IPython cell. | def run_cell(self, raw_cell, store_history=False, silent=False):
"""Run a complete IPython cell.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell ... |
Run a sequence of AST nodes. The execution mode depends on the interactivity parameter. | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
"""Run a sequence of AST nodes. The execution mode depends on the
interactivity parameter.
Parameters
----------
nodelist : list
A sequence of AST nodes to run.
cell_name : str
W... |
Execute a code object. | def run_code(self, code_obj):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to display a
traceback.
Parameters
----------
code_obj : code object
A compiled code object, to be executed
Returns
-------
... |
Activate pylab support at runtime. | def enable_pylab(self, gui=None, import_all=True):
"""Activate pylab support at runtime.
This turns on support for matplotlib, preloads into the interactive
namespace all of numpy and pylab, and configures IPython to correctly
interact with the GUI event loop. The GUI backend to be use... |
Expand python variables in a string. | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is alway... |
Make a new tempfile and return its filename. | def mktempfile(self, data=None, prefix='ipython_edit_'):
"""Make a new tempfile and return its filename.
This makes a call to tempfile.mktemp, but it registers the created
filename internally so ipython cleans it up at exit time.
Optional inputs:
- data(None): if data is giv... |
Return as a string a set of input history slices. | def extract_input_lines(self, range_str, raw=False):
"""Return as a string a set of input history slices.
Parameters
----------
range_str : string
The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
since this function is for use by magic functions wh... |
Get a code string from history file url or a string or macro. | def find_user_code(self, target, raw=True, py_only=False):
"""Get a code string from history, file, url, or a string or macro.
This is mainly used by magic functions.
Parameters
----------
target : str
A string specifying code to retrieve. This will be tried respect... |
This will be executed at the time of exit. | def atexit_operations(self):
"""This will be executed at the time of exit.
Cleanup operations and saving of persistent data that is done
unconditionally by IPython should be performed here.
For things that may depend on startup flags or platform specifics (such
as having readli... |
broadcast a message from one engine to all others. | def broadcast(client, sender, msg_name, dest_name=None, block=None):
"""broadcast a message from one engine to all others."""
dest_name = msg_name if dest_name is None else dest_name
client[sender].execute('com.publish(%s)'%msg_name, block=None)
targets = client.ids
targets.remove(sender)
return... |
send a message from one to one - or - more engines. | def send(client, sender, targets, msg_name, dest_name=None, block=None):
"""send a message from one to one-or-more engines."""
dest_name = msg_name if dest_name is None else dest_name
def _send(targets, m_name):
msg = globals()[m_name]
return com.send(targets, msg)
client[sender... |
Make function raise SkipTest exception if a given condition is true. | def skipif(skip_condition, msg=None):
"""
Make function raise SkipTest exception if a given condition is true.
If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the test suite is ... |
Make function raise KnownFailureTest exception if given condition is true. | def knownfailureif(fail_condition, msg=None):
"""
Make function raise KnownFailureTest exception if given condition is true.
If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the ... |
Filter deprecation warnings while running the test suite. | def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, to avoid
printing them during the test suite run, while checking that the test
actually raises a DeprecationWarning.
Parameters
-------... |
list profiles in a given root directory | def list_profiles_in(path):
"""list profiles in a given root directory"""
files = os.listdir(path)
profiles = []
for f in files:
full_path = os.path.join(path, f)
if os.path.isdir(full_path) and f.startswith('profile_'):
profiles.append(f.split('_',1)[-1])
return profiles |
list profiles that are bundled with IPython. | def list_bundled_profiles():
"""list profiles that are bundled with IPython."""
path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
files = os.listdir(path)
profiles = []
for profile in files:
full_path = os.path.join(path, profile)
if os.path.isdir(full_path) and p... |
Sandbox - bypassing version of ensure_directory () | def _bypass_ensure_directory(path, mode=0o777):
"""Sandbox-bypassing version of ensure_directory()"""
if not WRITE_SUPPORT:
raise IOError('"os.mkdir" not supported on this platform.')
dirname, filename = split(path)
if dirname and filename and not isdir(dirname):
_bypass_ensure_directory... |
Find a distribution matching requirement req | def find(self, req):
"""Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
do... |
List all distributions needed to ( recursively ) meet requirements | def resolve(self, requirements, env=None, installer=None,
replace_conflicting=False):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
... |
Validate text as a PEP 426 environment marker ; return an exception if invalid or False otherwise. | def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
"""
try:
cls.evaluate_marker(text)
except SyntaxError:
return cls.normalize_exception(sys.exc_info()[1])
... |
This function runs the given command ; waits for it to finish ; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched. | def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None,
logfile=None, cwd=None, env=None, encoding='utf-8'):
"""
This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the co... |
This takes a given filename ; tries to find it in the environment path ; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. | def which (filename):
"""This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None."""
# Special case where filename already contains a path.
if os.path.dir... |
This starts the given command in a child process. This does all the fork/ exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed ( split on spaces ) and args will be set to parsed arguments. | def _spawn(self,command,args=[]):
"""This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set to parsed arguments. """
#... |
This implements a substitute for the forkpty system call. This should be more portable than the pty. fork () function. Specifically this should work on Solaris. | def __fork_pty(self):
"""This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue wit... |
This makes the pseudo - terminal the controlling tty. This should be more portable than the pty. fork () function. Specifically this should work on Solaris. | def __pty_make_controlling_tty(self, tty_fd):
"""This makes the pseudo-terminal the controlling tty. This should be
more portable than the pty.fork() function. Specifically, this should
work on Solaris. """
child_name = os.ttyname(tty_fd)
# Disconnect from controlling tty. Har... |
This closes the connection with the child application. Note that calling close () more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated ( SIGKILL is sent if the child ignores SIGHUP and SIGINT ). | def close (self, force=True): # File-like object.
"""This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SI... |
This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho (). | def getecho (self):
"""This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho(). """
attr = termios.tcgetattr(self.child_fd)
if attr[3] & te... |
This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost so you should be sure that your input buffer is empty before you call setecho (). For example the following will work as expected:: | def setecho (self, state):
"""This sets the terminal echo mode on or off. Note that anything the
child sent before the echo will be lost, so you should be sure that
your input buffer is empty before you call setecho(). For example, the
following will work as expected::
p = ... |
This reads at most size bytes from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog () then all data will also be written to the lo... | def read_nonblocking (self, size = 1, timeout = -1):
"""This reads at most size bytes from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be r... |
This reads at most size bytes from the file ( less if the read hits EOF before obtaining size bytes ). If the size argument is negative or omitted read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. | def read (self, size = -1): # File-like object.
"""This reads at most "size" bytes from the file (less if the read hits
EOF before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a string object. An... |
This reads and returns one entire line. A trailing newline is kept in the string but may be absent when a file ends with an incomplete line. Note: This readline () looks for a \\ r \\ n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline ... | def readline(self, size = -1):
"""This reads and returns one entire line. A trailing newline is kept
in the string, but may be absent when a file ends with an incomplete
line. Note: This readline() looks for a \\r\\n pair even on UNIX
because this is what the pseudo tty device returns. S... |
This is to support iterators over a file - like object. | def next (self): # File-like object.
"""This is to support iterators over a file-like object.
"""
result = self.readline()
if result == self._empty_buffer:
raise StopIteration
return result |
This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log. | def send(self, s):
"""This sends a string to the child process. This returns the number of
bytes written. If a log file was set then the data is also written to
the log. """
time.sleep(self.delaybeforesend)
s2 = self._cast_buffer_type(s)
if self.logfile is not ... |
This sends a control character to the child such as Ctrl - C or Ctrl - D. For example to send a Ctrl - G ( ASCII 7 ):: | def sendcontrol(self, char):
"""This sends a control character to the child such as Ctrl-C or
Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
child.sendcontrol('g')
See also, sendintr() and sendeof().
"""
char = char.lower()
a = ord(char)
if a>=9... |
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end - of - line. If it is the first character of the line the read () in the user program returns 0 which signifies end - of - file. This means to work as expe... | def sendeof(self):
"""This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which s... |
This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. | def sendintr(self):
"""This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. """
if hasattr(termios, 'VINTR'):
char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
else:
# platform does not define VINTR so ass... |
This compiles a pattern - string or a list of pattern - strings. Patterns must be a StringType EOF TIMEOUT SRE_Pattern or a list of those. Patterns may also be None which results in an empty list ( you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern ). | def compile_pattern_list(self, patterns):
"""This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TI... |
Recompile unicode regexes as bytes regexes. Overridden in subclass. | def _prepare_regex_pattern(self, p):
"Recompile unicode regexes as bytes regexes. Overridden in subclass."
if isinstance(p.pattern, unicode):
p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
return p |
This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType EOF a compiled re or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this return... | def expect(self, pattern, timeout = -1, searchwindowsize=-1):
"""This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled... |
This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT ( which are not compiled regular expressions ). This method is similar to the expect () method except that expect_list () does not recompile the pattern l... | def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
"""This takes a list of compiled regular expressions and returns the
index into the pattern_list that matched the child output. The list may
also contain EOF or TIMEOUT (which are not compiled regular
expressions)... |
This is similar to expect () but uses plain string matching instead of compiled regular expressions in pattern_list. The pattern_list may be a string ; a list or other sequence of strings ; or TIMEOUT and EOF. | def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
"""This is similar to expect(), but uses plain string matching instead
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
may be a string; a list or other sequence of strings; or TIMEOUT and
EO... |
This is the common loop used inside expect. The searcher should be an instance of searcher_re or searcher_string which describes how and what to search for in the input. | def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
"""This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and what
to search for in the input.
See expect() for other arguments, return... |
This returns the terminal window size of the child tty. The return value is a tuple of ( rows cols ). | def getwinsize(self):
"""This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols). """
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
r... |
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY - aware applications like vi or curses -- applications that respond to the SIGWINCH signal. | def setwinsize(self, r, c):
"""This sets the terminal window size of the child tty. This will cause
a SIGWINCH signal to be sent to the child. This does not change the
physical window size. It changes the size reported to TTY-aware
applications like vi or curses -- applications that res... |
This gives control of the child process to the interactive user ( the human at the keyboard ). Keystrokes are sent to the child process and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin.... | def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None):
"""This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is printed. ... |
This is used by the interact () method. | def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
"""This is used by the interact() method.
"""
while self.isalive():
r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
if self.child_fd in r:
da... |
This is a wrapper around select. select () that ignores signals. If select. select raises a select. error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch ( terminal resize ). | def __select (self, iwtd, owtd, ewtd, timeout=None):
"""This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). """
... |
Recompile bytes regexes as unicode regexes. | def _prepare_regex_pattern(self, p):
"Recompile bytes regexes as unicode regexes."
if isinstance(p.pattern, bytes):
p = re.compile(p.pattern.decode(self.encoding), p.flags)
return p |
This searches buffer for the first occurence of one of the search strings. freshlen must indicate the number of bytes at the end of buffer which have not been searched before. It helps to avoid searching the same possibly big buffer over and over again. | def search(self, buffer, freshlen, searchwindowsize=None):
"""This searches 'buffer' for the first occurence of one of the search
strings. 'freshlen' must indicate the number of bytes at the end of
'buffer' which have not been searched before. It helps to avoid
searching the same, poss... |
This searches buffer for the first occurence of one of the regular expressions. freshlen must indicate the number of bytes at the end of buffer which have not been searched before. | def search(self, buffer, freshlen, searchwindowsize=None):
"""This searches 'buffer' for the first occurence of one of the regular
expressions. 'freshlen' must indicate the number of bytes at the end of
'buffer' which have not been searched before.
See class spawn for the 'searchwindow... |
Finish up all displayhook activities. | def finish_displayhook(self):
"""Finish up all displayhook activities."""
sys.stdout.flush()
sys.stderr.flush()
self.session.send(self.pub_socket, self.msg, ident=self.topic)
self.msg = None |
Progress Monitor listener that logs all updates to the given logger | def log_listener(log:logging.Logger=None, level=logging.INFO):
"""Progress Monitor listener that logs all updates to the given logger"""
if log is None:
log = logging.getLogger("ProgressMonitor")
def listen(monitor):
name = "{}: ".format(monitor.name) if monitor.name is not None else ""
... |
Unpack a directory using the same interface as for archives | def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % (f... |
Unpack tar/ tar. gz/ tar. bz2 filename to extract_dir | def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
"""Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` a... |
Emit a message to the user. | def emit(self, msg, level=1, debug=False):
"""
Emit a message to the user.
:param msg: The message to emit. If ``debug`` is ``True``,
the message will be emitted to ``stderr`` only if
the ``debug`` attribute is ``True``. If ``debug``
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.