简体   繁体   中英

Call Jupyter Notebook magic command programmatically, from script

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM