问题
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