Created
February 1, 2014 03:39
-
-
Save fperez/8747615 to your computer and use it in GitHub Desktop.
IPython Shell that can be embedded when called in a doctest run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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