2

You can call a magic command in Jupyter from a script as follows:

ipython = get_ipython()
mgc = ipython.run_line_magic

mgc(magic_name = "my_magic_command", line="line_to_call")

But if I try to do this with the HTML magic command:

mgc(magic_name = "%%html", line="<iframe src='my_url' width='100%' height='400'></iframe>")

I get the following error:

UsageError: Line magic function `%%%html` not found.

Makes me think I should remove one of the %:

mgc(magic_name = "%html", line="<iframe src='my_url' width='100%' height='400'>")

UsageError: Line magic function `%%html` not found.

...or remove both %:

mgc(magic_name = "html", line="<iframe src='my_url' width='100%' height='400'>")

UsageError: Line magic function `%html` not found (But cell magic `%%html` exists, did you mean that instead?).

This might have something to do with the order of imports, but I cannot seem to resolve the issue.

Cybernetic
  • 12,628
  • 16
  • 93
  • 132

1 Answers1

0

The error message is quite instructive:

UsageError: Line magic function `%html` not found
(But cell magic `%%html` exists, did you mean that instead?).

There's a difference between "line magic" and "cell magic" functions. Let's use the run_cell_magic() function:

ipython = get_ipython()
ipython.run_cell_magic("html", "", "<iframe src='https://stackoverflow.com' width='100%' height='400'></iframe>")

The first parameter is the cell magic function name without the leading %%, the second parameter is the rest of the first line (we leave it empty), the third parameter is the HTML snipped you wish to show.

For details refer to the IPython documentation of run_cell_magic().

András Aszódi
  • 8,948
  • 5
  • 48
  • 51