Skip to content

Instantly share code, notes, and snippets.

@fperez
Created February 1, 2014 03:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fperez/8747615 to your computer and use it in GitHub Desktop.
Save fperez/8747615 to your computer and use it in GitHub Desktop.
IPython Shell that can be embedded when called in a doctest run
"""Implement a version of `IPython.embed()` which works during doctesting.
This provides a `dt_embed()` function that is similar to `IPython.embed`, but
which can run when used inside code that will be run via doctests (where the
default `embed` locks up due to the hijacking of `sys.stdout` that doctest
performs.
See https://github.com/ipython/ipython/issues/90 for the full details.
"""
def dt_embed(*a):
"""IPython shell embeddable inside a doctest.
"""
import sys
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.utils import io
class DTShell(InteractiveShellEmbed):
def __call__(self, *a, **kw):
sys_stdout = sys.stdout
io_stdout = io.stdout
sys.stdout = io.stdout = sys.stderr
try:
super(DTShell, self).__call__(*a, **kw)
finally:
sys.stdout = sys_stdout
io.stdout = io_stdout
# Create and call the shell
shell = DTShell()
shell(*a, stack_depth=3)
# Example usage
def some_function():
"""
>>> some_function()
'someoutput'
"""
# now try to drop into an ipython shell to help with development
x = 'hi ipython'
dt_embed("Check the value of `x`:")
y = 'another local'
dt_embed("Now look at `y`:")
return 'someoutput'
if __name__ == '__main__':
import doctest
print "Running doctest . . ."
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment