def can_use_widgets():
""" Expanded from from http://stackoverflow.com/a/34092072/1958900
"""
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return False
from IPython import get_ipython
# check for `kernel` attribute on the IPython instance
if getattr(get_ipython(), 'kernel', None) is None:
return False
try:
import ipywidgets as ipy
import traitlets
except ImportError:
return False
if int(ipy.__version__.split('.')[0]) < 6:
print('WARNING: widgets require ipywidgets 6.0 or later')
return False
return True
python类get_ipython()的实例源码
widget_utils.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def page(data, start=0, screen_lines=0, pager_cmd=None):
"""Display content in a pager, piping through a pager after a certain length.
data can be a mime-bundle dict, supplying multiple representations,
keyed by mime-type, or text.
Pager is dispatched via the `show_in_pager` IPython hook.
If no hook is registered, `pager_page` will be used.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
# first, try the hook
ip = get_ipython()
if ip:
try:
ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
return
except TryNext:
pass
# fallback on default pager
return pager_page(data, start, screen_lines, pager_cmd)
def test_latex_completions():
from IPython.core.latex_symbols import latex_symbols
import random
ip = get_ipython()
# Test some random unicode symbols
keys = random.sample(latex_symbols.keys(), 10)
for k in keys:
text, matches = ip.complete(k)
nt.assert_equal(len(matches),1)
nt.assert_equal(text, k)
nt.assert_equal(matches[0], latex_symbols[k])
# Test a more complex line
text, matches = ip.complete(u'print(\\alpha')
nt.assert_equal(text, u'\\alpha')
nt.assert_equal(matches[0], latex_symbols['\\alpha'])
# Test multiple matching latex symbols
text, matches = ip.complete(u'\\al')
nt.assert_in('\\alpha', matches)
nt.assert_in('\\aleph', matches)
def test_abspath_file_completions():
ip = get_ipython()
with TemporaryDirectory() as tmpdir:
prefix = os.path.join(tmpdir, 'foo')
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = [prefix+s for s in suffixes]
nt.assert_equal(c, comp)
def test_local_file_completions():
ip = get_ipython()
with TemporaryWorkingDirectory():
prefix = './foo'
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = set(prefix+s for s in suffixes)
nt.assert_true(comp.issubset(set(c)))
def test_line_cell_magics():
from IPython.core.magic import register_line_cell_magic
@register_line_cell_magic
def _bar_cellm(line, cell):
pass
ip = get_ipython()
c = ip.Completer
# The policy here is trickier, see comments in completion code. The
# returned values depend on whether the user passes %% or not explicitly,
# and this will show a difference if the same name is both a line and cell
# magic.
s, matches = c.complete(None, '_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%%_bar_ce')
nt.assert_not_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
def test_magic_color():
ip = get_ipython()
c = ip.Completer
s, matches = c.complete(None, 'colo')
nt.assert_in('%colors', matches)
s, matches = c.complete(None, 'colo')
nt.assert_not_in('NoColor', matches)
s, matches = c.complete(None, 'colors ')
nt.assert_in('NoColor', matches)
s, matches = c.complete(None, '%colors ')
nt.assert_in('NoColor', matches)
s, matches = c.complete(None, 'colors NoCo')
nt.assert_list_equal(['NoColor'], matches)
s, matches = c.complete(None, '%colors NoCo')
nt.assert_list_equal(['NoColor'], matches)
def test_dict_key_completion_unicode_py3():
"""Test handling of unicode in dict key completion"""
ip = get_ipython()
complete = ip.Completer.complete
ip.user_ns['d'] = {u'a\u05d0': None}
# query using escape
if sys.platform != 'win32':
# Known failure on Windows
_, matches = complete(line_buffer="d['a\\u05d0")
nt.assert_in("u05d0", matches) # tokenized after \\
# query using character
_, matches = complete(line_buffer="d['a\u05d0")
nt.assert_in(u"a\u05d0", matches)
with greedy_completion():
# query using escape
_, matches = complete(line_buffer="d['a\\u05d0")
nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
# query using character
_, matches = complete(line_buffer="d['a\u05d0")
nt.assert_in(u"d['a\u05d0']", matches)
def test_dict_key_completion_invalids():
"""Smoke test cases dict key completion can't handle"""
ip = get_ipython()
complete = ip.Completer.complete
ip.user_ns['no_getitem'] = None
ip.user_ns['no_keys'] = []
ip.user_ns['cant_call_keys'] = dict
ip.user_ns['empty'] = {}
ip.user_ns['d'] = {'abc': 5}
_, matches = complete(line_buffer="no_getitem['")
_, matches = complete(line_buffer="no_keys['")
_, matches = complete(line_buffer="cant_call_keys['")
_, matches = complete(line_buffer="empty['")
_, matches = complete(line_buffer="name_error['")
_, matches = complete(line_buffer="d['\\") # incomplete escape
def test_tb_syntaxerror():
"""test %tb after a SyntaxError"""
ip = get_ipython()
ip.run_cell("for")
# trap and validate stdout
save_stdout = sys.stdout
try:
sys.stdout = StringIO()
ip.run_cell("%tb")
out = sys.stdout.getvalue()
finally:
sys.stdout = save_stdout
# trim output, and only check the last line
last_line = out.rstrip().splitlines()[-1].strip()
nt.assert_equal(last_line, "SyntaxError: invalid syntax")
def doctest_precision():
"""doctest for %precision
In [1]: f = get_ipython().display_formatter.formatters['text/plain']
In [2]: %precision 5
Out[2]: {u}'%.5f'
In [3]: f.float_format
Out[3]: {u}'%.5f'
In [4]: %precision %e
Out[4]: {u}'%e'
In [5]: f(3.1415927)
Out[5]: {u}'3.141593e+00'
"""
def test_file_amend():
"""%%file -a amends files"""
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file2')
ip.run_cell_magic("file", fname, u'\n'.join([
'line1',
'line2',
]))
ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
'line3',
'line4',
]))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line3\n', s)
def test_line_cell_info():
"""%%foo and %foo magics are distinguishable to inspect"""
ip = get_ipython()
ip.magics_manager.register(FooFoo)
oinfo = ip.object_inspect('foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
oinfo = ip.object_inspect('%%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
oinfo = ip.object_inspect('%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
def test_alias_magic():
"""Test %alias_magic."""
ip = get_ipython()
mm = ip.magics_manager
# Basic operation: both cell and line magics are created, if possible.
ip.run_line_magic('alias_magic', 'timeit_alias timeit')
nt.assert_in('timeit_alias', mm.magics['line'])
nt.assert_in('timeit_alias', mm.magics['cell'])
# --cell is specified, line magic not created.
ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
nt.assert_in('timeit_cell_alias', mm.magics['cell'])
# Test that line alias is created successfully.
ip.run_line_magic('alias_magic', '--line env_alias env')
nt.assert_equal(ip.run_line_magic('env', ''),
ip.run_line_magic('env_alias', ''))
# Test that line alias with parameters passed in is created successfully.
ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
nt.assert_in('history_alias', mm.magics['line'])
def test_save():
"""Test %save."""
ip = get_ipython()
ip.history_manager.reset() # Clear any existing history.
cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
for i, cmd in enumerate(cmds, start=1):
ip.history_manager.store_inputs(i, cmd)
with TemporaryDirectory() as tmpdir:
file = os.path.join(tmpdir, "testsave.py")
ip.run_line_magic("save", "%s 1-10" % file)
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 1)
nt.assert_in('coding: utf-8', content)
ip.run_line_magic("save", "-a %s 1-10" % file)
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 2)
nt.assert_in('coding: utf-8', content)
def test_store():
"""Test %store."""
ip = get_ipython()
ip.run_line_magic('load_ext', 'storemagic')
# make sure the storage is empty
ip.run_line_magic('store', '-z')
ip.user_ns['var'] = 42
ip.run_line_magic('store', 'var')
ip.user_ns['var'] = 39
ip.run_line_magic('store', '-r')
nt.assert_equal(ip.user_ns['var'], 42)
ip.run_line_magic('store', '-d var')
ip.user_ns['var'] = 39
ip.run_line_magic('store' , '-r')
nt.assert_equal(ip.user_ns['var'], 39)
def _run_edit_test(arg_s, exp_filename=None,
exp_lineno=-1,
exp_contents=None,
exp_is_temp=None):
ip = get_ipython()
M = code.CodeMagics(ip)
last_call = ['','']
opts,args = M.parse_options(arg_s,'prxn:')
filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
if exp_filename is not None:
nt.assert_equal(exp_filename, filename)
if exp_contents is not None:
with io.open(filename, 'r', encoding='utf-8') as f:
contents = f.read()
nt.assert_equal(exp_contents, contents)
if exp_lineno != -1:
nt.assert_equal(exp_lineno, lineno)
if exp_is_temp is not None:
nt.assert_equal(exp_is_temp, is_temp)
def test_pass_correct_include_exclude():
class Tester(object):
def __init__(self, include=None, exclude=None):
self.include = include
self.exclude = exclude
def _repr_mimebundle_(self, include, exclude, **kwargs):
if include and (include != self.include):
raise ValueError('include got modified: display() may be broken.')
if exclude and (exclude != self.exclude):
raise ValueError('exclude got modified: display() may be broken.')
return None
include = {'a', 'b', 'c'}
exclude = {'c', 'e' , 'f'}
f = get_ipython().display_formatter
f.format(Tester(include=include, exclude=exclude), include=include, exclude=exclude)
f.format(Tester(exclude=exclude), exclude=exclude)
f.format(Tester(include=include), include=include)
def quick_completer(cmd, completions):
""" Easily create a trivial completer for a command.
Takes either a list of completions, or all completions in string (that will
be split on whitespace).
Example::
[d:\ipython]|1> import ipy_completers
[d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
[d:\ipython]|3> foo b<TAB>
bar baz
[d:\ipython]|3> foo ba
"""
if isinstance(completions, str):
completions = completions.split()
def do_complete(self, event):
return completions
get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
def can_use_widgets():
""" Expanded from from http://stackoverflow.com/a/34092072/1958900
"""
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return False
from IPython import get_ipython
# check for `kernel` attribute on the IPython instance
if getattr(get_ipython(), 'kernel', None) is None:
return False
try:
import ipywidgets as ipy
import traitlets
except ImportError:
return False
return True
def page(data, start=0, screen_lines=0, pager_cmd=None):
"""Display content in a pager, piping through a pager after a certain length.
data can be a mime-bundle dict, supplying multiple representations,
keyed by mime-type, or text.
Pager is dispatched via the `show_in_pager` IPython hook.
If no hook is registered, `pager_page` will be used.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
# first, try the hook
ip = get_ipython()
if ip:
try:
ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
return
except TryNext:
pass
# fallback on default pager
return pager_page(data, start, screen_lines, pager_cmd)
def test_latex_completions():
from IPython.core.latex_symbols import latex_symbols
import random
ip = get_ipython()
# Test some random unicode symbols
keys = random.sample(latex_symbols.keys(), 10)
for k in keys:
text, matches = ip.complete(k)
nt.assert_equal(len(matches),1)
nt.assert_equal(text, k)
nt.assert_equal(matches[0], latex_symbols[k])
# Test a more complex line
text, matches = ip.complete(u'print(\\alpha')
nt.assert_equals(text, u'\\alpha')
nt.assert_equals(matches[0], latex_symbols['\\alpha'])
# Test multiple matching latex symbols
text, matches = ip.complete(u'\\al')
nt.assert_in('\\alpha', matches)
nt.assert_in('\\aleph', matches)
def test_abspath_file_completions():
ip = get_ipython()
with TemporaryDirectory() as tmpdir:
prefix = os.path.join(tmpdir, 'foo')
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = [prefix+s for s in suffixes]
nt.assert_equal(c, comp)
def test_local_file_completions():
ip = get_ipython()
with TemporaryWorkingDirectory():
prefix = './foo'
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = set(prefix+s for s in suffixes)
nt.assert_true(comp.issubset(set(c)))
def test_line_cell_magics():
from IPython.core.magic import register_line_cell_magic
@register_line_cell_magic
def _bar_cellm(line, cell):
pass
ip = get_ipython()
c = ip.Completer
# The policy here is trickier, see comments in completion code. The
# returned values depend on whether the user passes %% or not explicitly,
# and this will show a difference if the same name is both a line and cell
# magic.
s, matches = c.complete(None, '_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%%_bar_ce')
nt.assert_not_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
def test_struct_array_key_completion():
"""Test dict key completion applies to numpy struct arrays"""
import numpy
ip = get_ipython()
complete = ip.Completer.complete
ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
_, matches = complete(line_buffer="d['")
nt.assert_in("hello", matches)
nt.assert_in("world", matches)
# complete on the numpy struct itself
dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
('my_data', '>f4', 5)])
x = numpy.zeros(2, dtype=dt)
ip.user_ns['d'] = x[1]
_, matches = complete(line_buffer="d['")
nt.assert_in("my_head", matches)
nt.assert_in("my_data", matches)
# complete on a nested level
with greedy_completion():
ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
_, matches = complete(line_buffer="d[1]['my_head']['")
nt.assert_true(any(["my_dt" in m for m in matches]))
nt.assert_true(any(["my_df" in m for m in matches]))
def test_dict_key_completion_invalids():
"""Smoke test cases dict key completion can't handle"""
ip = get_ipython()
complete = ip.Completer.complete
ip.user_ns['no_getitem'] = None
ip.user_ns['no_keys'] = []
ip.user_ns['cant_call_keys'] = dict
ip.user_ns['empty'] = {}
ip.user_ns['d'] = {'abc': 5}
_, matches = complete(line_buffer="no_getitem['")
_, matches = complete(line_buffer="no_keys['")
_, matches = complete(line_buffer="cant_call_keys['")
_, matches = complete(line_buffer="empty['")
_, matches = complete(line_buffer="name_error['")
_, matches = complete(line_buffer="d['\\") # incomplete escape
def test_tb_syntaxerror():
"""test %tb after a SyntaxError"""
ip = get_ipython()
ip.run_cell("for")
# trap and validate stdout
save_stdout = sys.stdout
try:
sys.stdout = StringIO()
ip.run_cell("%tb")
out = sys.stdout.getvalue()
finally:
sys.stdout = save_stdout
# trim output, and only check the last line
last_line = out.rstrip().splitlines()[-1].strip()
nt.assert_equal(last_line, "SyntaxError: invalid syntax")
def doctest_precision():
"""doctest for %precision
In [1]: f = get_ipython().display_formatter.formatters['text/plain']
In [2]: %precision 5
Out[2]: {u}'%.5f'
In [3]: f.float_format
Out[3]: {u}'%.5f'
In [4]: %precision %e
Out[4]: {u}'%e'
In [5]: f(3.1415927)
Out[5]: {u}'3.141593e+00'
"""
def test_file_amend():
"""%%file -a amends files"""
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file2')
ip.run_cell_magic("file", fname, u'\n'.join([
'line1',
'line2',
]))
ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
'line3',
'line4',
]))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line3\n', s)