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 ...
IPython’s in-built magic functions are extremely powerful. There are two types of magic functions. Line magics, which work very much like DOS commands. Cell magics, which work on multiple lines of code. We shall learn about line magic functions and cell magic functions in detail in subsequent chapters.
When using Jupyter Notebook with IPython kernel, IPython magic commands come in handy. These magic commands make it easier to complete certain tasks. You can think of them as an extra set of helpful syntax in addition to Python syntax. In this post, we will get familiar with a few useful magic commands that you could use in Jupyter Notebook.
Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow. They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes.
IPython filters your input and converts it all into valid Python source before executing it (things like magics or aliases are turned into function calls, for example). With this option, you’ll see the native history instead of the user-entered version: ‘%cd /’ will be seen as ‘get_ipython ().run_line_magic (“cd”, “/”)’ instead of ‘%cd /’.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With