how does IPython magics work

怎甘沉沦 提交于 2019-12-23 12:34:17

问题


ipthon-sql is an extension of ipython, I first install it by pip install ipython-sql

the project is here: https://github.com/catherinedevlin/ipython-sql

and my problem is:

when I enter %load_ext sql and press SHIFT+ENTER, what's the detailed procedure of IPython to execute this magic sentence? thanks ...


回答1:


When you run any code in the notebook, an execute_request is sent via the notebook server, to a 'kernel', a process which executes your code.

When the kernel receives your code, it runs it through a sequence of input transformers. One of these detects that this line is a magic command, and rewrites it to:

get_ipython().magic('load_ext sql')

You can see these translated commands using %hist -t.

The .magic() method takes the first word of its argument, load_ext, and looks it up in a dictionary. You can see that dictionary by running:

get_ipython().magics_manager.magics['line']

(this may be a bit different depending on your version of IPython)

That gives it a reference to the method IPython.core.magics.extension.ExtensionMagics.load_ext, which you can see here. It calls that method with the remainder of the string.

That method imports the package sql, and calls sql.load_ipython_extension(ip) to set it up. It's up to the extension what it does then - in this case, it registers some new magic functions.



来源:https://stackoverflow.com/questions/29251180/how-does-ipython-magics-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!