Last active
January 9, 2020 04:15
-
-
Save creallfluharty/13ac0f54929b608c6ebfc97ea33cb6a4 to your computer and use it in GitHub Desktop.
Get IPython magic command output
This file contains 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
import io | |
from contextlib import redirect_stdout | |
from typing import Optional | |
from IPython.core.interactiveshell import InteractiveShell #just for the type annotation | |
from IPython.core.magic import register_line_magic | |
@register_line_magic # so that we can optionally use get_magic_out as a magic command | |
def get_magic_out(command: str, ipy: Optional[InteractiveShell]=None) -> str: | |
""" Redirects the stdout of a ipython magic command to a temporary buffer | |
Args: | |
command: The command to be executed, as if it were in the shell. | |
ie `get_magic_out('history 5')` would capture the output of the command | |
``` | |
In [1]: %history 5 | |
``` | |
ipy (optional): The ipython shell to run the command in. Defaults to getting | |
the current shell (by calling `get_ipython` which is bound to the current shell) | |
Returns: | |
The output of %{command} | |
""" | |
ipy = ipy or get_ipython() | |
out = io.StringIO() | |
with redirect_stdout(out): | |
ipy.magic(command) | |
return out.getvalue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
X-Reference: https://stackoverflow.com/a/59657049/11411686