访问单元格内的其他单元格内容 (Colab)

时间:2021-06-21 11:53:36

标签: python jupyter-notebook google-colaboratory

来自德国的大家下午好!

Google Colab 和我似乎对什么是可能的或不可能有不同的看法...... 我只是想要一种从单元格内访问所有其他单元格内容的方法。

我的用例是,我想将当前 Colab Notebook 的内容发布到外部服务器,以便以最少的用户交互(仅运行单元)进行评分。

所以我的问题是:有没有办法以编程方式访问 Colab NB 的代码单元?

我看到了 Jupyter NB 的 this answer,但它在 Google Colab 中不起作用,因为 Jupyter JS-Variable 不可用。变量 google.colab 似乎没有提供相同的功能,还是我遗漏了什么?

Google Colab 似乎在其一个 iframe 中对每个单元格进行沙盒处理,因此我无法通过 JS 查询其他单元格的内容:

    %%js
    document.getElementsByClassName('cell')

在单元格中运行时,这只会导致一个空的 HTMLCollection,当在浏览器的开发人员工具中运行时,我得到了正确的结果。

我在这里遗漏了什么吗?有没有办法逃脱沙箱或访问 Python 单元格中的当前 NB 内容?

预先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

可能不是理想的解决方案 - 但一种选择可能是直接读取笔记本文件,而不是尝试在内部访问单元格。以下代码将用户的 google 驱动器挂载到笔记本中,以便您可以将其内容作为文件读取:

from pathlib import Path
from google.colab import drive

# Mount the users google drive into the notebook (takes the
# user to an auth flow for access).
drive.mount('/content/drive')

# Read the contents of the notebook file to POST to grading server.
base = Path('/content/drive/MyDrive/Colab Notebooks')
notebook_path = 'notebook.ipynb'
with open(base / notebook_path) as infile:
  notebook_contents = infile.read()

找到笔记本的路径似乎很棘手,但如果它有一个标准名称,您可以使用 base.rpath('*.ipynb') 搜索它并向用户提供一些要提交的文件选项。

答案 1 :(得分:1)

当然,这是一个完整的例子: https://colab.research.google.com/drive/1mXuyMsPEXFU4ik9EGLBiWUuNfztf7J6_

关键是:

# Obtain the notebook JSON as a string
from google.colab import _message
notebook_json_string = _message.blocking_request('get_ipynb', request='', timeout_sec=5)

从笔记本中复制执行的示例:

enter image description here

相关问题