How do I define custom magics in jupyter?

妖精的绣舞 提交于 2019-12-01 11:29:05

There are two separate things here:

  1. startup files are scripts in ~/.ipython/profile_[name]/startup that are executed as part of starting IPython. They are treated as if you %run each of them prior to the first In[1] prompt. Startup files cannot be imported, because they are not on sys.path.
  2. extensions are Python modules that can be imported and define a load_ipython_extension function. You can put extensions in ~/.ipython/extensions and they will be importable, or you can install them as regular packages with pip.

The first fix is to move your cppmagics to ~/.ipython/extensions or to some site-packages directory, so that it is importable.

If you really want the magics always registered (rather than calling %load_ext cppmagic), you can leave it as a startup file and register the magic at the end of the script, instead of def load_ipython_extension:

if __name__ == '__main__':
    from IPython import get_ipython
    get_ipython().register_magics(CppMagics)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!