简体   繁体   English

jupyter笔记本 - 检查魔法是否可用

[英]jupyter notebook - check if magic is available

I am trying to call a python command from within javascript using the ipykernel.comm. 我试图使用ipykernel.comm在javascript中调用python命令。 The problem is that I want to use the same code regardless if I run python3 kernel or pyspark3 kernel. 问题是我想使用相同的代码,无论我运行python3内核还是pyspark3内核。 For the latter I need to run code with %%local cell magic, which does not work for the pure python 3 kernel. 对于后者,我需要使用%% local cell magic运行代码,这对于纯python 3内核不起作用。

How do I programmatically check if a given (frontend) magic is available? 如何以编程方式检查给定(前端)魔法是否可用?

I tried looking into get_ipython().magics_manager.registry but I feel that is not the way. 我试着查看get_ipython().magics_manager.registry但我觉得这不是问题。 I tried to look on the frontend (javascript) side but I also could not find it. 我试着看一下前端(javascript),但我也找不到它。

I thought maybe the source for sparkmagic will help me, but no luck. 我想也许sparkmagic的来源会帮助我,但没有运气。 I do not know how to access IPython.CodeCell.config_defaults 我不知道如何访问IPython.CodeCell.config_defaults

sparkmagic's kernel.js sparkmagic的kernel.js

Instead of checking if the command is available you just use it and catch the exception if it is not supported. 而不是检查命令是否可用,您只需使用它并捕获异常(如果不支持)。

Example: 例:

from IPython.core.error import UsageError
try:
    %%local
except UsageError:
    print("Magic %%local not support in this kernel")

You can get the available magics via: 您可以通过以下方式获得可用的魔法:

from IPython import get_ipython

line_magics = list(get_ipython().magics_manager.magics.get('line'))
cell_magics = list(get_ipython().magics_manager.magics.get('cell'))

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

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