##// END OF EJS Templates
Fix the right inputhook...
Fix the right inputhook Interactive shell and debugger have similar code. The fix was applied to the wrong one, not sure how test were passing.

File last commit:

r25189:6c5d9c3e
r25325:bcc84fb0
Show More
basic.py
652 lines | 22.1 KiB | text/x-python | PythonLexer
MinRK
update IPython.core to nbformat 4...
r18585 """Implementation of basic magic functions."""
Fernando Perez
Create core.magics.basic according to new API.
r6959
Thomas Kluyver
Deprecate -e flag for %notebook magic...
r22796 import argparse
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 from logging import error
Fernando Perez
Create core.magics.basic according to new API.
r6959 import io
from pprint import pformat
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 import textwrap
import sys
from warnings import warn
Fernando Perez
Create core.magics.basic according to new API.
r6959
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 from traitlets.utils.importstring import import_item
Thomas Kluyver
Remove unused imports from IPython.core
r11124 from IPython.core import magic_arguments, page
Fernando Perez
Create core.magics.basic according to new API.
r6959 from IPython.core.error import UsageError
Bradley M. Froehle
Add dictionary for magic escape sequences.
r7704 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
Bradley M. Froehle
Fix indentation of help text in %magic.
r8005 from IPython.utils.text import format_screen, dedent, indent
Fernando Perez
Create core.magics.basic according to new API.
r6959 from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.ipstruct import Struct
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688 class MagicsDisplay(object):
Matthias Bussonnier
Insert a fake pip magic warning users the should use the shell....
r23362 def __init__(self, magics_manager, ignore=None):
self.ignore = ignore if ignore else []
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688 self.magics_manager = magics_manager
def _lsmagic(self):
"""The main implementation of the %lsmagic"""
mesc = magic_escapes['line']
cesc = magic_escapes['cell']
mman = self.magics_manager
magics = mman.lsmagic()
out = ['Available line magics:',
Matthias Bussonnier
Insert a fake pip magic warning users the should use the shell....
r23362 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688 '',
'Available cell magics:',
Matthias Bussonnier
Insert a fake pip magic warning users the should use the shell....
r23362 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688 '',
mman.auto_status()]
return '\n'.join(out)
def _repr_pretty_(self, p, cycle):
p.text(self._lsmagic())
def __str__(self):
return self._lsmagic()
def _jsonable(self):
"""turn magics dict into jsonable dict of the same structure
replaces object instances with their class names as strings
"""
magic_dict = {}
mman = self.magics_manager
magics = mman.lsmagic()
for key, subdict in magics.items():
d = {}
magic_dict[key] = d
for name, obj in subdict.items():
try:
Thomas Kluyver
Fix method special attributes...
r13370 classname = obj.__self__.__class__.__name__
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688 except AttributeError:
classname = 'Other'
d[name] = classname
return magic_dict
def _repr_json_(self):
Min RK
JSON formatter expects JSONable dict/list...
r19557 return self._jsonable()
MinRK
%lsmagic returns a RichRepr of the magics dict...
r10688
Fernando Perez
Renamed @register_magics to @magics_class to avoid confusion....
r6973 @magics_class
Fernando Perez
Create core.magics.basic according to new API.
r6959 class BasicMagics(Magics):
"""Magics that provide central IPython functionality.
These are various magics that don't fit into specific categories but that
are all part of the base 'IPython experience'."""
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 @magic_arguments.magic_arguments()
@magic_arguments.argument(
'-l', '--line', action='store_true',
help="""Create a line magic alias."""
)
@magic_arguments.argument(
'-c', '--cell', action='store_true',
help="""Create a cell magic alias."""
)
@magic_arguments.argument(
'name',
help="""Name of the magic to be created."""
)
@magic_arguments.argument(
'target',
help="""Name of the existing line or cell magic."""
)
Nick Weseman
ENH: Add alias_magic parameters
r23639 @magic_arguments.argument(
'-p', '--params', default=None,
help="""Parameters passed to the magic function."""
)
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 @line_magic
def alias_magic(self, line=''):
Bradley M. Froehle
Add %alias_magic examples (t -> timeit, whereami -> pwd).
r7722 """Create an alias for an existing line or cell magic.
Examples
--------
::
Thomas Kluyver
Fix documentation of functions using magic_arguments
r13604
Bradley M. Froehle
Add %alias_magic examples (t -> timeit, whereami -> pwd).
r7722 In [1]: %alias_magic t timeit
Bradley M. Froehle
`%alias_magic` print a message for each new alias.
r7934 Created `%t` as an alias for `%timeit`.
Created `%%t` as an alias for `%%timeit`.
Bradley M. Froehle
Add %alias_magic examples (t -> timeit, whereami -> pwd).
r7722
In [2]: %t -n1 pass
1 loops, best of 3: 954 ns per loop
In [3]: %%t -n1
...: pass
...:
1 loops, best of 3: 954 ns per loop
In [4]: %alias_magic --cell whereami pwd
UsageError: Cell magic function `%%pwd` not found.
In [5]: %alias_magic --line whereami pwd
Bradley M. Froehle
`%alias_magic` print a message for each new alias.
r7934 Created `%whereami` as an alias for `%pwd`.
Bradley M. Froehle
Add %alias_magic examples (t -> timeit, whereami -> pwd).
r7722
In [6]: %whereami
Out[6]: u'/home/testuser'
Nick Weseman
ENH: Add alias_magic parameters
r23639
mfh92
typo fix...
r25189 In [7]: %alias_magic h history "-p -l 30" --line
Nick Weseman
ENH: Add alias_magic parameters
r23639 Created `%h` as an alias for `%history -l 30`.
Bradley M. Froehle
Add %alias_magic examples (t -> timeit, whereami -> pwd).
r7722 """
Nick Weseman
ENH: Add alias_magic parameters
r23639
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 args = magic_arguments.parse_argstring(self.alias_magic, line)
shell = self.shell
Bradley M. Froehle
%alias_magic: Use mman.register_alias API for creating new magic aliases.
r7932 mman = self.shell.magics_manager
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 escs = ''.join(magic_escapes.values())
target = args.target.lstrip(escs)
name = args.name.lstrip(escs)
Nick Weseman
ENH: Add alias_magic parameters
r23639 params = args.params
if (params and
((params.startswith('"') and params.endswith('"'))
or (params.startswith("'") and params.endswith("'")))):
params = params[1:-1]
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 # Find the requested magics.
m_line = shell.find_magic(target, 'line')
m_cell = shell.find_magic(target, 'cell')
if args.line and m_line is None:
raise UsageError('Line magic function `%s%s` not found.' %
(magic_escapes['line'], target))
if args.cell and m_cell is None:
raise UsageError('Cell magic function `%s%s` not found.' %
(magic_escapes['cell'], target))
# If --line and --cell are not specified, default to the ones
# that are available.
if not args.line and not args.cell:
if not m_line and not m_cell:
raise UsageError(
'No line or cell magic with name `%s` found.' % target
)
args.line = bool(m_line)
args.cell = bool(m_cell)
Nick Weseman
ENH: Add alias_magic parameters
r23639 params_str = "" if params is None else " " + params
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705 if args.line:
Nick Weseman
ENH: Add alias_magic parameters
r23639 mman.register_alias(name, target, 'line', params)
print('Created `%s%s` as an alias for `%s%s%s`.' % (
Bradley M. Froehle
`%alias_magic` print a message for each new alias.
r7934 magic_escapes['line'], name,
Nick Weseman
ENH: Add alias_magic parameters
r23639 magic_escapes['line'], target, params_str))
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705
if args.cell:
Nick Weseman
ENH: Add alias_magic parameters
r23639 mman.register_alias(name, target, 'cell', params)
print('Created `%s%s` as an alias for `%s%s%s`.' % (
Bradley M. Froehle
`%alias_magic` print a message for each new alias.
r7934 magic_escapes['cell'], name,
Nick Weseman
ENH: Add alias_magic parameters
r23639 magic_escapes['cell'], target, params_str))
Bradley M. Froehle
Add %alias_magic for creating magic aliases.
r7705
Fernando Perez
Create core.magics.basic according to new API.
r6959 @line_magic
def lsmagic(self, parameter_s=''):
"""List currently available magic functions."""
Matthias Bussonnier
Update basic.py
r24887 return MagicsDisplay(self.shell.magics_manager, ignore=[])
Fernando Perez
Create core.magics.basic according to new API.
r6959
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652 def _magic_docs(self, brief=False, rest=False):
"""Return docstrings from magic functions."""
mman = self.shell.magics_manager
docs = mman.lsmagic_docs(brief, missing='No documentation')
if rest:
Bradley M. Froehle
Fix indentation of help text in %magic.
r8005 format_string = '**%s%s**::\n\n%s\n\n'
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652 else:
Bradley M. Froehle
Fix indentation of help text in %magic.
r8005 format_string = '%s%s:\n%s\n'
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652
return ''.join(
Bradley M. Froehle
Fix indentation of help text in %magic.
r8005 [format_string % (magic_escapes['line'], fname,
indent(dedent(fndoc)))
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652 for fname, fndoc in sorted(docs['line'].items())]
+
Bradley M. Froehle
Fix indentation of help text in %magic.
r8005 [format_string % (magic_escapes['cell'], fname,
indent(dedent(fndoc)))
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652 for fname, fndoc in sorted(docs['cell'].items())]
)
Fernando Perez
Create core.magics.basic according to new API.
r6959 @line_magic
def magic(self, parameter_s=''):
"""Print information about the magic function system.
Supported formats: -latex, -brief, -rest
"""
mode = ''
try:
mode = parameter_s.split()[0][1:]
Fernando Perez
Small fixes as per @certik's review.
r6986 except IndexError:
Fernando Perez
Create core.magics.basic according to new API.
r6959 pass
Bradley M. Froehle
Refactor %magic into a lsmagic_docs API function.
r7652 brief = (mode == 'brief')
rest = (mode == 'rest')
magic_docs = self._magic_docs(brief, rest)
Fernando Perez
Create core.magics.basic according to new API.
r6959
if mode == 'latex':
print(self.format_latex(magic_docs))
return
else:
magic_docs = format_screen(magic_docs)
out = ["""
IPython's 'magic' functions
===========================
The magic function system provides a series of functions which allow you to
control the behavior of IPython itself, plus a lot of system-type
Fernando Perez
Document cell magics in %magic....
r7005 features. There are two kinds of magics, line-oriented and cell-oriented.
Line magics are prefixed with the % character and work much like OS
command-line calls: they get as an argument the rest of the line, where
arguments are passed without parentheses or quotes. For example, this will
time the given statement::
%timeit range(1000)
Cell magics are prefixed with a double %%, and they are functions that get as
an argument not only the rest of the line, but also the lines below it in a
separate argument. These magics are called with two arguments: the rest of the
call line and the body of the cell, consisting of the lines below the first.
For example::
%%timeit x = numpy.random.randn((100, 100))
numpy.linalg.svd(x)
will time the execution of the numpy svd routine, running the assignment of x
as part of the setup phase, which is not timed.
In a line-oriented client (the terminal or Qt console IPython), starting a new
input with %% will automatically enter cell mode, and IPython will continue
reading input until a blank line is given. In the notebook, simply type the
whole cell as one entity, but keep in mind that the %% escape can only be at
the very start of the cell.
Fernando Perez
Create core.magics.basic according to new API.
r6959
NOTE: If you have 'automagic' enabled (via the command line option or with the
Fernando Perez
Document cell magics in %magic....
r7005 %automagic function), you don't need to type in the % explicitly for line
magics; cell magics always require an explicit '%%' escape. By default,
Fernando Perez
Create core.magics.basic according to new API.
r6959 IPython ships with automagic on, so you should only rarely need the % escape.
lingxz
change a minor typo in magic docs
r21677 Example: typing '%cd mydir' (without the quotes) changes your working directory
Fernando Perez
Create core.magics.basic according to new API.
r6959 to 'mydir', if it exists.
For a list of the available magic functions, use %lsmagic. For a description
of any of them, type %magic_name?, e.g. '%cd?'.
Currently the magic system has the following functions:""",
magic_docs,
Bradley M. Froehle
%magic: Fix `%slsmagic` typo.
r8006 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
MinRK
fix `%magic` output...
r10994 str(self.lsmagic()),
Fernando Perez
Create core.magics.basic according to new API.
r6959 ]
page.page('\n'.join(out))
@line_magic
def page(self, parameter_s=''):
"""Pretty print the object and display it through a pager.
%page [options] OBJECT
If no object is given, use _ (last output).
Options:
-r: page str(object), don't pretty-print it."""
# After a function contributed by Olivier Aubert, slightly modified.
# Process options/args
opts, args = self.parse_options(parameter_s, 'r')
raw = 'r' in opts
oname = args and args or '_'
MinRK
fix _ofind attr in %page...
r7638 info = self.shell._ofind(oname)
Fernando Perez
Create core.magics.basic according to new API.
r6959 if info['found']:
txt = (raw and str or pformat)( info['obj'] )
page.page(txt)
else:
print('Object `%s` not found' % oname)
@line_magic
def pprint(self, parameter_s=''):
"""Toggle pretty printing on/off."""
ptformatter = self.shell.display_formatter.formatters['text/plain']
ptformatter.pprint = bool(1 - ptformatter.pprint)
print('Pretty printing has been turned',
['OFF','ON'][ptformatter.pprint])
@line_magic
def colors(self, parameter_s=''):
"""Switch color scheme for prompts, info system and exception handlers.
Currently implemented schemes: NoColor, Linux, LightBG.
Color scheme names are not case-sensitive.
Examples
--------
To get a plain black and white terminal::
%colors nocolor
"""
def color_switch_err(name):
warn('Error changing %s color schemes.\n%s' %
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 (name, sys.exc_info()[1]), stacklevel=2)
Fernando Perez
Create core.magics.basic according to new API.
r6959
new_scheme = parameter_s.strip()
if not new_scheme:
raise UsageError(
"%colors: you must specify a color scheme. See '%colors?'")
# local shortcut
shell = self.shell
Thomas Kluyver
Remove outdated colors_force attribute
r22608 # Set shell colour scheme
try:
shell.colors = new_scheme
shell.refresh_style()
except:
color_switch_err('shell')
Fernando Perez
Create core.magics.basic according to new API.
r6959
# Set exception colors
try:
shell.InteractiveTB.set_colors(scheme = new_scheme)
shell.SyntaxTB.set_colors(scheme = new_scheme)
except:
color_switch_err('exception')
# Set info (for 'object?') colors
if shell.color_info:
try:
shell.inspector.set_active_scheme(new_scheme)
except:
color_switch_err('object inspector')
else:
shell.inspector.set_active_scheme('NoColor')
@line_magic
def xmode(self, parameter_s=''):
"""Switch modes for the exception handlers.
Dan Allan
ENH: Add a 'Minimal' xmode option....
r24849 Valid modes: Plain, Context, Verbose, and Minimal.
Fernando Perez
Create core.magics.basic according to new API.
r6959
If called without arguments, acts as a toggle."""
def xmode_switch_err(name):
warn('Error changing %s exception modes.\n%s' %
(name,sys.exc_info()[1]))
shell = self.shell
new_mode = parameter_s.strip().capitalize()
try:
shell.InteractiveTB.set_mode(mode=new_mode)
print('Exception reporting mode:',shell.InteractiveTB.mode)
except:
xmode_switch_err('user')
Matthias Bussonnier
Insert a fake pip magic warning users the should use the shell....
r23362 @line_magic
def quickref(self, arg):
Fernando Perez
Create core.magics.basic according to new API.
r6959 """ Show a quick reference sheet """
from IPython.core.usage import quick_reference
Bradley M. Froehle
%magic -brief: print, rather than return, the result.
r7653 qr = quick_reference + self._magic_docs(brief=True)
Fernando Perez
Create core.magics.basic according to new API.
r6959 page.page(qr)
@line_magic
def doctest_mode(self, parameter_s=''):
"""Toggle doctest mode on and off.
This mode is intended to make IPython behave as much as possible like a
plain Python shell, from the perspective of how its prompts, exceptions
and output look. This makes it easy to copy and paste parts of a
session into doctests. It does so by:
- Changing the prompts to the classic ``>>>`` ones.
- Changing the exception reporting mode to 'Plain'.
- Disabling pretty-printing of output.
Note that IPython also supports the pasting of code snippets that have
leading '>>>' and '...' prompts in them. This means that you can paste
doctests from files or docstrings (even if they have leading
whitespace), and the code will execute correctly. You can then use
'%history -t' to see the translated history; this will give you the
input after removal of all the leading prompts and whitespace, which
can be pasted back into an editor.
With these features, you can switch into this mode easily whenever you
need to do testing and changes to doctests, without having to leave
your existing IPython session.
"""
# Shorthands
shell = self.shell
meta = shell.meta
disp_formatter = self.shell.display_formatter
ptformatter = disp_formatter.formatters['text/plain']
# dstore is a data store kept in the instance metadata bag to track any
# changes we make, so we can undo them later.
dstore = meta.setdefault('doctest_mode',Struct())
save_dstore = dstore.setdefault
# save a few values we'll need to recover later
mode = save_dstore('mode',False)
save_dstore('rc_pprint',ptformatter.pprint)
save_dstore('xmode',shell.InteractiveTB.mode)
save_dstore('rc_separate_out',shell.separate_out)
save_dstore('rc_separate_out2',shell.separate_out2)
save_dstore('rc_separate_in',shell.separate_in)
MinRK
propagate deprecation of Formatter.plain_text_only
r9814 save_dstore('rc_active_types',disp_formatter.active_types)
Fernando Perez
Create core.magics.basic according to new API.
r6959
Rémy Léone
Simplify boolean expression
r21779 if not mode:
Fernando Perez
Create core.magics.basic according to new API.
r6959 # turn on
# Prompt separators like plain python
shell.separate_in = ''
shell.separate_out = ''
shell.separate_out2 = ''
ptformatter.pprint = False
MinRK
propagate deprecation of Formatter.plain_text_only
r9814 disp_formatter.active_types = ['text/plain']
Fernando Perez
Create core.magics.basic according to new API.
r6959
shell.magic('xmode Plain')
else:
# turn off
shell.separate_in = dstore.rc_separate_in
shell.separate_out = dstore.rc_separate_out
shell.separate_out2 = dstore.rc_separate_out2
ptformatter.pprint = dstore.rc_pprint
MinRK
propagate deprecation of Formatter.plain_text_only
r9814 disp_formatter.active_types = dstore.rc_active_types
Fernando Perez
Create core.magics.basic according to new API.
r6959
shell.magic('xmode ' + dstore.xmode)
Thomas Kluyver
Switch prompts for doctest_mode
r22429 # mode here is the state before we switch; switch_doctest_mode takes
# the mode we're switching to.
shell.switch_doctest_mode(not mode)
Fernando Perez
Create core.magics.basic according to new API.
r6959 # Store new mode and inform
Thomas Kluyver
Switch prompts for doctest_mode
r22429 dstore.mode = bool(not mode)
Fernando Perez
Create core.magics.basic according to new API.
r6959 mode_label = ['OFF','ON'][dstore.mode]
print('Doctest mode is:', mode_label)
@line_magic
def gui(self, parameter_s=''):
"""Enable or disable IPython GUI event loop integration.
%gui [GUINAME]
This magic replaces IPython's threaded shells that were activated
using the (pylab/wthread/etc.) command line flags. GUI toolkits
can now be enabled at runtime and keyboard
interrupts should work without any problems. The following toolkits
are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
%gui wx # enable wxPython event loop integration
%gui qt4|qt # enable PyQt4 event loop integration
Stefan Zimmermann
%gui qt5
r17904 %gui qt5 # enable PyQt5 event loop integration
Fernando Perez
Create core.magics.basic according to new API.
r6959 %gui gtk # enable PyGTK event loop integration
%gui gtk3 # enable Gtk3 event loop integration
%gui tk # enable Tk event loop integration
Bradley M. Froehle
Add 'osx' as a command-line option for --gui=.
r7097 %gui osx # enable Cocoa event loop integration
Fernando Perez
Create core.magics.basic according to new API.
r6959 # (requires %matplotlib 1.1)
%gui # disable all event loop integration
WARNING: after any of these has been called you can simply create
an application object, but DO NOT start the event loop yourself, as
we have already handled that.
"""
opts, arg = self.parse_options(parameter_s, '')
if arg=='': arg = None
try:
MinRK
fix %gui...
r7091 return self.shell.enable_gui(arg)
Fernando Perez
Create core.magics.basic according to new API.
r6959 except Exception as e:
# print simple error message, rather than traceback if we can't
# hook up the GUI
error(str(e))
@skip_doctest
@line_magic
def precision(self, s=''):
"""Set floating point precision for pretty printing.
Can set either integer precision or a format string.
If numpy has been imported and precision is an int,
numpy display precision will also be set, via ``numpy.set_printoptions``.
If no argument is given, defaults will be restored.
Examples
--------
::
In [1]: from math import pi
In [2]: %precision 3
Out[2]: u'%.3f'
In [3]: pi
Out[3]: 3.142
In [4]: %precision %i
Out[4]: u'%i'
In [5]: pi
Out[5]: 3
In [6]: %precision %e
Out[6]: u'%e'
In [7]: pi**10
Out[7]: 9.364805e+04
In [8]: %precision
Out[8]: u'%r'
In [9]: pi**10
Out[9]: 93648.047476082982
"""
ptformatter = self.shell.display_formatter.formatters['text/plain']
ptformatter.float_precision = s
return ptformatter.float_format
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-e', '--export', action='store_true', default=False,
Thomas Kluyver
Deprecate -e flag for %notebook magic...
r22796 help=argparse.SUPPRESS
Fernando Perez
Create core.magics.basic according to new API.
r6959 )
@magic_arguments.argument(
Srinivas Reddy Thatiparthy
remove unicode_type function
r23044 'filename', type=str,
Fernando Perez
Create core.magics.basic according to new API.
r6959 help='Notebook name or filename'
)
@line_magic
def notebook(self, s):
"""Export and convert IPython notebooks.
MinRK
update IPython.core to nbformat 4...
r18585 This function can export the current IPython history to a notebook file.
Thomas Kluyver
Deprecate -e flag for %notebook magic...
r22796 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
The -e or --export flag is deprecated in IPython 5.2, and will be
removed in the future.
Fernando Perez
Create core.magics.basic according to new API.
r6959 """
args = magic_arguments.parse_argstring(self.notebook, s)
Min RK
jupyter_nbformat is now nbformat
r21345 from nbformat import write, v4
Thomas Kluyver
Deprecate -e flag for %notebook magic...
r22796
cells = []
hist = list(self.shell.history_manager.get_range())
if(len(hist)<=1):
raise ValueError('History is empty, cannot export')
for session, execution_count, source in hist[:-1]:
cells.append(v4.new_code_cell(
execution_count=execution_count,
source=source
))
nb = v4.new_notebook(cells=cells)
with io.open(args.filename, 'w', encoding='utf-8') as f:
write(nb, f, version=4)
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467
@magics_class
class AsyncMagics(BasicMagics):
@line_magic
def autoawait(self, parameter_s):
"""
Allow to change the status of the autoawait option.
This allow you to set a specific asynchronous code runner.
If no value is passed, print the currently used asynchronous integration
and whether it is activated.
It can take a number of value evaluated in the following order:
- False/false/off deactivate autoawait integration
- True/true/on activate autoawait integration using configured default
loop
- asyncio/curio/trio activate autoawait integration and use integration
with said library.
Matthias Bussonnier
Add pseudo sync mode
r24481 - `sync` turn on the pseudo-sync integration (mostly used for
`IPython.embed()` which does not run IPython with a real eventloop and
deactivate running asynchronous code. Turning on Asynchronous code with
the pseudo sync loop is undefined behavior and may lead IPython to crash.
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467 If the passed parameter does not match any of the above and is a python
identifier, get said object from user namespace and set it as the
Matthias Bussonnier
Add pseudo sync mode
r24481 runner, and activate autoawait.
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467
If the object is a fully qualified object name, attempt to import it and
Matthias Bussonnier
docs cleanup, reformat code, remove dead code.
r24490 set it as the runner, and activate autoawait.
The exact behavior of autoawait is experimental and subject to change
across version of IPython and Python.
"""
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467
param = parameter_s.strip()
d = {True: "on", False: "off"}
if not param:
print("IPython autoawait is `{}`, and set to use `{}`".format(
d[self.shell.autoawait],
self.shell.loop_runner
))
return None
if param.lower() in ('false', 'off'):
self.shell.autoawait = False
return None
if param.lower() in ('true', 'on'):
self.shell.autoawait = True
return None
if param in self.shell.loop_runner_map:
Matthias Bussonnier
Add pseudo sync mode
r24481 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467 return None
if param in self.shell.user_ns :
self.shell.loop_runner = self.shell.user_ns[param]
self.shell.autoawait = True
return None
runner = import_item(param)
self.shell.loop_runner = runner
self.shell.autoawait = True