Inheritance diagram for IPython.core.interactiveshell:
Main IPython class.
Bases: IPython.config.configurable.SingletonConfigurable
An enhanced, interactive shell for Python.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
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.
An enum that whose value must be in a given sequence.
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 readline or not), register a separate atexit function in the code that has the appropriate information, rather than trying to clutter
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. This helps the user understand that the input line was transformed automatically by IPython.
An enum that whose value must be in a given sequence.
A casting version of the boolean trait.
A casting version of the boolean trait.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
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.
This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). This way, for multiple executions of the same script we only keep one copy of the namespace (the last one), thus preventing memory leaks from old references while allowing the objects from the last execution to be accessible.
Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a copy of the given namespace, to allow the original module’s __dict__ to be cleared and reused.
Parameters : | ns : a namespace (a dict, typically)
|
---|
Examples
In [10]: import IPython
In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
In [12]: IPython.__file__ in _ip._main_ns_cache Out[12]: True
An integer trait.
Longs that are unnecessary (<= sys.maxint) are cast to ints.
Control auto-activation of pdb at exceptions
Get the config class config section
Get the help string for this class in ReST format.
If inst is given, it’s current trait values will be used in place of class defaults.
Get the help string for a single trait.
If inst is given, it’s current trait values will be used in place of the class default.
Get the help string for a single trait and print it.
Get a list of all the names of this classes traits.
This method is just like the trait_names() method, but is unbound.
Get a list of all the traits of this class.
This method is just like the traits() method, but is unbound.
The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.
unset _instance for this class and singleton parents.
Clear the cache of main modules.
Mainly for use by utilities like %reset.
Examples
In [15]: import IPython
In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
In [17]: len(_ip._main_ns_cache) > 0 Out[17]: True
In [18]: _ip.clear_main_mod_cache()
In [19]: len(_ip._main_ns_cache) == 0 Out[19]: True
A casting version of the boolean trait.
An enum of strings that are caseless in validate.
A casting version of the boolean trait.
Return the completed text and a list of completions.
Parameters : | text : string
|
---|---|
Returns : | text : string
The optional arguments allow the completion to take more context into : account, and are part of the low-level completion API. : This is a wrapper around the completion mechanism, similar to what : readline does at the command line when the TAB key is hit. By : exposing it as a method, it can be used by other non-readline : environments (such as GUIs) for text completion. : Simple usage example: : In [1]: x = ‘hello’ : In [2]: _ip.complete(‘x.l’) : Out[2]: (‘x.l’, [‘x.ljust’, ‘x.lower’, ‘x.lstrip’]) : |
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A casting version of the boolean trait.
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 the flag is false.
A casting version of the boolean trait.
Define a new macro
Parameters : | name : str
themacro : str or Macro
|
---|
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
by_name : bool
|
---|
A casting version of the boolean trait.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A trait whose value must be a subclass of a specified class.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A trait whose value must be a subclass of a specified class.
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
|
---|
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 used can be optionally selected with the optional :param:`gui` argument.
Parameters : | gui : optional, string
|
---|
Evaluate python expression expr in user namespace.
Returns the result of evaluation
Execute a normal python statement in user namespace.
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 mainloop. This is a bother for IPython which excepts to catch all of the program exceptions with a try: except: statement.
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes.
This hook should be used sparingly, only in places which are not likely to be true IPython errors.
An integer trait.
Longs that are unnecessary (<= sys.maxint) are cast to ints.
A casting version of the boolean trait.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Return as a string a set of input history slices.
Parameters : | range_str : string
Optional Parameters: :
Note that slices can be called with two notations: : N:M -> standard python form, means including items N...(M-1). : N-M -> include items N..M (closed endpoint). : |
---|
A trait for unicode strings.
Find and return a cell magic by name.
Returns None if the magic isn’t found.
Find and return a line magic by name.
Returns None if the magic isn’t found.
Find and return a magic of the given type by name.
Returns None if the magic isn’t found.
Get a code string from history, file, url, or a string or macro.
This is mainly used by magic functions.
Parameters : | target : str
raw : bool
py_only : bool (default False)
|
---|---|
Returns : | A string of code. : ValueError is raised if nothing is found, and TypeError if it evaluates : to an object of another type. In each case, .args[0] is a printable : message. : |
Return the currently running IPython instance.
Get output (possibly including stderr) from a subprocess.
Parameters : | cmd : str
split : bool, optional
depth : int, optional
|
---|
An integer trait.
Longs that are unnecessary (<= sys.maxint) are cast to ints.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
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 (typically over the network by remote frontends).
Any changes we need to make to the user’s environment.
Sets up the command history, and starts regular autosaves.
Initialize logging in case it was requested at the command line.
Command history completion/saving/reloading.
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 method. If they were not empty before, data will simply be added to therm.
Add a virtualenv to sys.path so the user can import modules from it. This isn’t perfect: it doesn’t use the Python interpreter with which the virtualenv was built, and it ignores the –no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough.
Adapted from code snippets online.
Has an instance been created?
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Returns a global instance of this class.
This method create a new instance if none have previously been created and returns a previously created instance is one already exists.
The arguments and keyword arguments passed to this method are passed on to the __init__() method of the class upon instantiation.
Examples
Create a singleton class using instance, and retrieve it:
>>> from IPython.config.configurable import SingletonConfigurable
>>> class Foo(SingletonConfigurable): pass
>>> foo = Foo.instance()
>>> foo == Foo.instance()
True
Create a subclass that is retrived using the base class instance:
>>> class Bar(SingletonConfigurable): pass
>>> class Bam(Bar): pass
>>> bam = Bam.instance()
>>> bam == Bar.instance()
True
A trait for unicode strings.
A trait for unicode strings.
A trait for unicode strings.
A casting version of the boolean trait.
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 the ipython prompt:
In[1]: %name -opt foo bar
To call a magic without arguments, simply use magic(‘name’).
This provides a proper Python function to call IPython’s magics in any valid Python code you can type at the interpreter, including loops and compound statements.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
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 given, it gets written out to the temp file
immediately, and the file is closed again.
A casting version of the boolean trait.
Return a new ‘main’ module object for user code execution.
An enum that whose value must be in a given sequence.
Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).
Parameters : | handler : callable
name : list, str, None
remove : bool
|
---|
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A casting version of the boolean trait.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
readline hook to be used at the start of each line.
Currently it handles auto-indent only.
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
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 created, and user_ns becomes the global namespace. If both are provided (as they may be when embedding), user_ns is the local namespace, and user_module provides the global namespace.
Parameters : | user_module : module, optional
user_ns : dict, optional
|
---|---|
Returns : | A tuple of user_module and user_ns, each properly initialised. : |
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
A trait for unicode strings.
A trait for unicode strings.
A trait for unicode strings.
A casting version of the boolean trait.
Inject a group of variables into the IPython user namespace.
Parameters : | variables : dict, str or list/tuple of str
interactive : bool
|
---|
A casting version of the boolean trait.
An instance of a Python list.
A trait for unicode strings.
A casting version of the boolean trait.
Register a function for calling after code execution.
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 selective variables from internal namespaces based on a specified regular expression.
Parameters : | regex : string or compiled pattern, optional
|
---|
Restore the state of the sys module.
Run a sequence of AST nodes. The execution mode depends on the interactivity parameter.
Parameters : | nodelist : list
cell_name : str
interactivity : str
|
---|
Run a complete IPython cell.
Parameters : | raw_cell : str
store_history : bool
silent : bool
|
---|
Execute the given cell magic.
Parameters : | magic_name : str
line : str
cell : str
|
---|
Execute a code object.
When an exception occurs, self.showtraceback() is called to display a traceback.
Parameters : | code_obj : code object
|
---|---|
Returns : | False : successful execution. True : an error occurred. |
Execute the given line magic.
Parameters : | magic_name : str
line : str
|
---|
Execute a code object.
When an exception occurs, self.showtraceback() is called to display a traceback.
Parameters : | code_obj : code object
|
---|---|
Returns : | False : successful execution. True : an error occurred. |
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 : | fname : string
where : tuple
exit_ignore : bool (False)
raise_exceptions : bool (False)
|
---|
Like safe_execfile, but for .ipy files with IPython syntax.
Parameters : | fname : str
|
---|
A safe version of runpy.run_module().
This version will never throw an exception, but instead print helpful error messages to the screen.
SystemExit exceptions with status code 0 or None are ignored.
Parameters : | mod_name : string
where : dict
|
---|
Save the state of hooks in the sys module.
This has to be called after self.user_module is created.
A Unicode subclass to validate separate_in, separate_out, etc.
This is a Unicode based trait that converts ‘0’->’’ and ‘n’->’
‘.
A Unicode subclass to validate separate_in, separate_out, etc.
This is a Unicode based trait that converts ‘0’->’’ and ‘n’->’
‘.
A Unicode subclass to validate separate_in, separate_out, etc.
This is a Unicode based trait that converts ‘0’->’’ and ‘n’->’
‘.
Set the autoindent flag, checking for readline support.
If called with no arguments, it acts as a toggle.
Set the frame of the completer.
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.
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 : | exc_tuple : tuple of exception classes
handler : callable
WARNING: by putting in your own exception handler into IPython’s main : execution loop, you run a very good chance of nasty crashes. This : facility should only be used if you really know what you are doing. : |
---|
IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython’s behavior to call at runtime your own routines.
Sets the ‘default’ input string for the next command line.
Requires readline.
Example:
[D:ipython]|1> _ip.set_next_input(“Hello Word”) [D:ipython]|2> Hello Word_ # cursor is here
Reset readline’s completer to be our own.
A casting version of the boolean trait.
Show a usage message
Called by run_cell when there’s an IndentationError in code entered at the prompt.
This is overridden in TerminalInteractiveShell to show a message about the %paste magic.
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 “<string>” when reading from a string).
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, rather than directly invoking the InteractiveTB object.
A specific showsyntaxerror() also exists, but this method can take care of calling it if needed, so unless you are explicitly catching a SyntaxError exception, don’t try to analyze the stack manually and simply call this method.
Call the given cmd in a subprocess, piping stdout/err
Parameters : | cmd : str
|
---|
Call the given cmd in a subprocess, piping stdout/err
Parameters : | cmd : str
|
---|
Call the given cmd in a subprocess using os.system
Parameters : | cmd : str
|
---|
Get metadata values for trait by key.
Get a list of all the names of this classes traits.
Get a list of all the traits of this class.
The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.
Fire the traits events when the config is updated.
Evaluate a dict of expressions in the user’s namespace.
Parameters : | expressions : dict
|
---|---|
Returns : | A dict, keyed like the input expressions dict, with the repr() of each : value. : |
Get a list of variable names from the user’s namespace.
Parameters : | names : list of strings
|
---|---|
Returns : | A dict, keyed by the input names and with the repr() of each value. : |
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 always the user’s interactive namespace.
A casting version of the boolean trait.
Write a string to the default output
Write a string to the default error output
An enum of strings that are caseless in validate.
Bases: object
Context manager to execute some code, then reload readline history so that interactive input to the code doesn’t appear when pressing up.
Get the last n items in readline history.
Bases: IPython.utils.traitlets.Unicode
A Unicode subclass to validate separate_in, separate_out, etc.
This is a Unicode based trait that converts ‘0’->’’ and ‘n’->’
‘.
Create a TraitType.
Create a new instance of the default value.
This is called by HasTraits.__new__() to finish init’ing.
Some stages of initialization must be delayed until the parent HasTraits instance has been created. This method is called in HasTraits.__new__() after the instance has been created.
This method trigger the creation and validation of default values and also things like the resolution of str given class names in Type and :class`Instance`.
Parameters : | obj : HasTraits instance
|
---|
Set the default value on a per instance basis.
This method is called by instance_init() to create and validate the default value. The creation and validation of default values must be delayed until the parent HasTraits class has been instantiated.