您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

首先是的,有可能以一种真正骇人听闻的方式获得相邻的markdown单元,这在无头笔记本执行中是行不通的。

您要执行的操作是使用IPython单元魔术,该魔术允许任意语法,只要该单元以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)

现在,您可以在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 A1
set foo TO Bar where ID=9

然后在您的Python单元中

MysqL.execute(__mystore.A1)

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

在您似乎要说的评论pig,没有什么可以阻止您拥有%%pig魔力的。也可以注入Javascript以启用sql和PIG的正确语法高亮显示,但这超出了此问题的范围。

python 2022/1/1 18:29:24 有186人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶