我认为您试图以错误的方式解决问题。
首先是的,有可能以非常骇人听闻的方式获取相邻的降价单元格,这在无头笔记本执行中不起作用。
您想要做的是使用 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 语法来命名您的单元格,例如,如果 _store 是 dict,或者更好的类您覆盖__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)
我还强烈建议查看 IPython 的 Catherine Develin SqlMagic,以及 GitHub 上的 Notebook gist,它可以实时展示这一切。
在评论中你似乎说你想添加pig,没有什么能阻止你拥有%%pig 魔法。也可以注入 Javascript 来启用 SQL 和 PIG 的正确语法突出显示,但这超出了这个问题的范围。