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

时间:2015-11-03 20:23:48

标签: python ipython ipython-notebook

我的ipython笔记本包含混合markdownpython个单元格。

我希望我的一些python单元格读取相邻的markdown单元格并将其作为输入处理。

所需情况的一个示例:

  

CELL 1(降价):要执行的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")

如何做到这一点?

1 个答案:

答案 0 :(得分:16)

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

首先,是的,有可能让相邻的降价单元以非常黑客的方式获得,这在无头笔记本执行中是行不通的。

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

通常您需要SQL单元格。

您可以参考有关cells magics的文档 或者我可以告诉你如何构建它:

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)

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

%%sql 
select * from foo Where QUX Bar

第二个细胞:

%%sql
Insert Cheezburger into Can_I_HAZ

检查我们执行了什么(3个破折号显示输入/输出分隔,您不必输入它们):

%showsql
---
['select * from foo Where QUX Bar', 'Insert Cheezburger into Can_I_HAZ']

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

 mysql.query(__mystore[-1])

这当然确实要求您按正确的顺序执行前面的单元格,没有什么可以阻止您使用%%sql语法来命名您的单元格,例如,如果_storedict或者更好的是覆盖__getattr__的类,像__getitem__一样使用点语法访问字段。这是留给读者的练习,或者最终看到答案:

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

然后您可以使用像

这样的SQL单元格
%%sql A1
set foo TO Bar where ID=9

然后在你的Python单元格中

mysql.execute(__mystore.A1)

我还强烈建议查看Catherine Develin SqlMagic IPython,以及GitHub上的这个Notebook gist显示所有内容。

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