简体   繁体   English

Jupyter Notebook,Python:从函数内调用魔术,而不仅仅是单元格

[英]Jupyter Notebook, Python: Call magic from within a function _not just a cell_

I am trying to write a library that will embed some JavaScript into a Jupyter notebook. 我正在尝试编写一个将一些JavaScript嵌入Jupyter笔记本的库。 The code works fine using %%javascript magic, but I want to embed the loading of the JavaScript into a library call. 使用%%javascript魔术,代码可以正常工作,但是我想将JavaScript的加载嵌入到库调用中。 I found this SO post: Jupyter Notebook, Python: How to call a magic from within a function? 我发现了这样的帖子: Jupyter Notebook,Python:如何从函数内部调用魔术? but it only partially works. 但它只能部分起作用。

The following code correctly runs the JavaScript alert: 以下代码正确运行JavaScript警报:

from IPython.core.magics.display import Javascript
Javascript('alert("hello world")')

The following, however, does not work (nothing happens; no console errors): 但是,以下操作不起作用(什么也没有发生;没有控制台错误):

from IPython.core.magics.display import Javascript

def foo():
    Javascript('alert("hello world")')
foo()

How do I embed a working call to Javascript within a function? 如何在函数中嵌入对Javascript的有效调用?

Shoot. 射击。 It's amazing how much more quickly your mind can work after posting to SO. 发布到SO 之后,您的思维可以更快地工作这真是令人惊讶。

For posterity, the Javascript function works with Jupyter by returning the necessary code. 为了后代, Javascript函数通过返回必要的代码与Jupyter一起使用。 In order to get my example working, the only change is to make foo return the result of Javascript(...) . 为了使我的示例正常工作,唯一的更改是使foo返回Javascript(...)的结果。 I was thinking of it as a void return with the work done within the function via some magical connection to the notebook. 我认为这是通过与笔记本的某种神奇连接而在函数内完成的工作的无效回报。 Not so! 不是这样! (Of course if this had been statically typed, I would known this and saved myself some time, but I digress.) Anwyay, the proper code is: (当然,如果它是静态类型的,我会知道这一点并为自己节省了一些时间,但是我离题了。)嗯,正确的代码是:

from IPython.core.magics.display import Javascript

def foo():
    return Javascript('alert("hello world")')
foo()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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