阅读 ipython 笔记本中的单元格内容

Read cell content in an ipython notebook

我有一个 ipython 笔记本,混合了 markdownpython 个单元格。

而且我希望我的一些 python 单元格读取相邻的 markdown 单元格并将它们作为输入进行处理。

期望情况的示例:

CELL 1 (markdown): SQL Code to execute

CELL 2 (markdown): 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")

如何做到这一点?

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

首先,是的,有可能以非常骇人听闻的方式获取相邻的降价单元格,这在无头笔记本执行中不起作用。

您想要做的是使用 IPython 单元格魔法,它允许任意语法,只要单元格以 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,或者更好的 class 覆盖 __getattr__,以像 __getitem__ 一样使用点语法访问字段。这留作 reader 的练习,或结束查看回复:

@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)

我还强烈建议在 GitHub 上查看 IPython, and this Notebook gist 的 Catherine Develin SqlMagic,它可以实时显示所有内容。

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