在ipython笔记本中读取单元格内容 [英] Read cell content in an ipython notebook

查看:91
本文介绍了在ipython笔记本中读取单元格内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ipython 笔记本,混合降价 python cells。

I have an ipython notebook with mixed markdown and python cells.

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

And I'd like some of my python cells to read the adjacent markdown cells and process them as input.

所需情况的示例:


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

CELL 1 (markdown): SQL Code to execute

CELL 2(降价)从tbl中选择*,其中x = 1

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

(语法 ipython.previous_cell.content 已组成)

执行 CELL 3 应相当于 mysql.query(select * from tbl,其中x = 1)

如何做到这一点?

推荐答案

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

I think you are trying to attack the problem the wrong way.

首先,是的,有可能以无法实现的方式获得相邻的降价单元,这在无头笔记本执行中无效。

First yes, it is possible to get the adjacent markdown cell in really hackish way that would not work in headless notebook execution.

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

What you want to do is use IPython cell magics, that allow arbitrary syntax as long as the cell starts with 2 percent signs followed by an identifier.

通常,您需要SQL单元格。

Typically you want SQL cells.

您可以参考有关 cell magics
或者我可以告诉你如何构建:

You can refer to the documentation about cells magics or I can show you how to build that :

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语法:

Now you can use SQL syntax in your python cells:

%%sql 
select * from foo Where QUX Bar

第二个单元格:

%%sql
Insert Cheezburger into Can_I_HAZ

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

check what we executed (the 3 dashes show the input /output delimitation, you do not have to type them):

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

你在问题​​的开头提出的问题:

And what you asked at the beginning in your question:

 mysql.query(__mystore[-1])

这当然要求你以正确的顺序执行前面的单元格,没有什么能阻止你使用 %% sql 命名单元格的语法,例如 _store 是一个 dict ,或者更好的一个类,你覆盖 __ getattr __ ,表现得像 __ getitem __ 访问带有点语法的字段。这是留给读者的练习,或者最终看到回复:

This of course does require that you execute the previous cells in the right order, nothing prevent you from using the %%sql syntax to name your cells, e.g if _store is a dict, or better a class where you overwrite __getattr__, to act like __getitem__ to access fields with dot syntax . This is left as an exercise to the reader, or end see of the response:

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

然后你就可以使用sql cell了

you can then use sql cell like

%%sql A1
set foo TO Bar where ID=9

然后在你的Python单元格中

And then in your Python cells

mysql.execute(__mystore.A1)

我还强烈建议您查看Catherine Develin SqlMagic以获取 IPython ,以及GitHub上的笔记本要点,可以显示所有内容。

I would also strongly suggest looking at Catherine Develin SqlMagic for IPython, and this Notebook gist on GitHub that show this all thing live.

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

In the comment you seem to say you want to add pig, nothing prevent you from having a %%pig magic neither. It is also possible to inject Javascript to enable correct Syntax Highlighting of SQL and PIG, but that's beyond the scope of this question.

这篇关于在ipython笔记本中读取单元格内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆