在ipython笔记本中读取单元格内容

Uri*_*ren 23 python ipython ipython-notebook

我有一个ipython混合markdownpython细胞笔记本.

我想让我的一些python细胞读取相邻的markdown细胞并将它们作为输入进行处理.

所需情况的一个例子:

CELL 1(markdown):要执行的SQL代码

CELL 2(降价):select * from tbl where x=1

CELL 3(python) :mysql.query(ipython.previous_cell.content)

(语法ipython.previous_cell.content组成)

执行" CELL 3 "应该相当于mysql.query("select * from tbl where x=1")

如何才能做到这一点 ?

Mat*_*att 18

我认为你试图以错误的方式解决问题.

首先,是的,有可能让相邻的降价单元格以真正的hackish方式在无头笔记本执行中无效.

你想要做的是使用IPython cell magics,它允许任意语法,只要单元格以2%符号开头,后跟一个标识符.

通常,您需要SQL单元格.

您可以参考有关单元格魔法的文档, 或者我可以向您展示如何构建它:

from IPython.core.magic import  (
    Magics, magics_class, cell_magic, line_magic
)

@magics_class
class StoreSQL(Magics):


    def __init__(self, shell=None,  **kwargs):
        super().__init__(shell=shell, **kwargs)
        self._store = []
        # inject our store in user availlable namespace under __mystore
        # name
        shell.user_ns['__mystore'] = self._store

    @cell_magic
    def sql(self, line, cell):
        """store the cell in the store"""
        self._store.append(cell)

    @line_magic
    def showsql(self, line):
        """show all recorded statements"""
        print(self._store)

    ## use ipython load_ext mechanisme here if distributed
    get_ipython().register_magics(StoreSQL)
Run Code Online (Sandbox Code Playgroud)

现在您可以在python单元格中使用SQL语法:

%%sql 
select * from foo Where QUX Bar
Run Code Online (Sandbox Code Playgroud)

第二个细胞:

%%sql
Insert Cheezburger into Can_I_HAZ
Run Code Online (Sandbox Code Playgroud)

检查我们执行的内容(3个破折号显示输入/输出分隔,您不必键入它们):

%showsql
---
['select * from foo Where QUX Bar', 'Insert Cheezburger into Can_I_HAZ']
Run Code Online (Sandbox Code Playgroud)

你在问题的开头问了什么:

 mysql.query(__mystore[-1])
Run Code Online (Sandbox Code Playgroud)

当然,这要求你按照正确的顺序执行前面的细胞,没有什么阻止你使用的%%sql语法来命名你的细胞,例如,如果_store是一个dict,或者更好的一类,你改写__getattr__,要像__getitem__用点语法接入领域.这是留给读者的练习,或者最终看到回复:

@cell_magic
def sql(self, line, cell):
    """store the cell in the store"""
    self._store[line.strip()] = cell
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用sql cell了

%%sql A1
set foo TO Bar where ID=9
Run Code Online (Sandbox Code Playgroud)

然后在你的Python单元格中

mysql.execute(__mystore.A1)
Run Code Online (Sandbox Code Playgroud)

我也强烈建议看着凯瑟琳Develin SqlMagic为IPython的,这笔记本要点在GitHub上,实况表演这一切事情.

在你似乎想要添加的评论中pig,没有任何东西阻止你拥有%%pig魔法.也可以注入Javascript以启用SQL和PIG的正确语法突出显示,但这超出了本问题的范围.