Valentas
Valentas

Reputation: 2245

ipython notebook: custom cells and execute hook

I would like to override what happens when run is pressed for certain cells in ipython notebook.

For example, I would like to be able to write an SQL query directly in a cell and define a function that processes it.

It seems it should be possible to do this as with ipython-notebook extensions. Does anyone know of a similar extension? An easy way to do this directly from ipython?

Ideally this would involve defining a custom cell type, but I would be happy to use special tags to separate the usual python code from, say, a custom SQL query cell.

Upvotes: 4

Views: 1611

Answers (1)

KT.
KT.

Reputation: 11430

I've once had the similar desire and I ended up with the following solution:

from sqlalchemy import create_engine
import pandas as pd
from IPython.core.magic import register_cell_magic
from IPython import get_ipython
con = create_engine(DB_URL)

@register_cell_magic
def sql(line, cell):
    cell = cell.format(**globals())
    if line.strip() != '-':
        res = pd.read_sql(cell, con)
        if line.strip() != '': get_ipython().user_ns[line.strip()] = res
        return res
    else:
        con.execute(cell)
del sql

You can now write in other cells:

%sql outputvar
select * from whatever where ...

For example:

Screenshot

Upvotes: 5

Related Questions