python - 通过 API 与 Jupyter Notebooks 交互

标签 python jupyter-notebook jupyter remote-access apache-zeppelin

问题:我想通过 Jupyter API 从另一个应用程序与 Jupyter 交互,特别是我想至少从该应用程序运行我的笔记本(对我来说完美的变体是在运行它之前编辑一些段落)。我读过 API documentation但还没有找到我需要的东西。

我已经为此目的使用了 Apache Zeppelin具有相同的结构(笔记本和段落)。

是否有人将 Jupyter 用于我刚才描述的目的?

最佳答案

忽略使用 Jupyter API 是否是问题的最佳解决方案(问题中未明确描述),下面的代码执行您所要求的:它将通过 http 远程执行 Jupyter notebook 并获得一些结果。它不是生产就绪的,它更像是一个如何完成的例子。没有用产生大量输出的单元测试它 - 认为它需要调整。

您还可以通过更改代码数组以编程方式更改/编辑代码。

您需要根据您的配置更改 notebook_path、base 和 headers,详情请参阅代码。

import json
import requests
import datetime
import uuid
from pprint import pprint
from websocket import create_connection

# The token is written on stdout when you start the notebook
notebook_path = '/Untitled.ipynb'
base = 'http://localhost:9999'
headers = {'Authorization': 'Token 4a72cb6f71e0f05a6aa931a5e0ec70109099ed0c35f1d840'}

url = base + '/api/kernels'
response = requests.post(url,headers=headers)
kernel = json.loads(response.text)

# Load the notebook and get the code of each cell
url = base + '/api/contents' + notebook_path
response = requests.get(url,headers=headers)
file = json.loads(response.text)
code = [ c['source'] for c in file['content']['cells'] if len(c['source'])>0 ]

# Execution request/reply is done on websockets channels
ws = create_connection("ws://localhost:9999/api/kernels/"+kernel["id"]+"/channels",
     header=headers)

def send_execute_request(code):
    msg_type = 'execute_request';
    content = { 'code' : code, 'silent':False }
    hdr = { 'msg_id' : uuid.uuid1().hex, 
        'username': 'test', 
        'session': uuid.uuid1().hex, 
        'data': datetime.datetime.now().isoformat(),
        'msg_type': msg_type,
        'version' : '5.0' }
    msg = { 'header': hdr, 'parent_header': hdr, 
        'metadata': {},
        'content': content }
    return msg

for c in code:
    ws.send(json.dumps(send_execute_request(c)))

# We ignore all the other messages, we just get the code execution output
# (this needs to be improved for production to take into account errors, large cell output, images, etc.)
for i in range(0, len(code)):
    msg_type = '';
    while msg_type != "stream":
        rsp = json.loads(ws.recv())
        msg_type = rsp["msg_type"]
    print(rsp["content"]["text"])

ws.close()

制作此代码所基于的有用链接(如果您想了解更多信息,我建议您阅读):

注意还有https://jupyter-client.readthedocs.io/en/stable/index.html ,但据我所知,它不支持将 HTTP 作为传输方式。

作为引用,这适用于 notebook-5.7.4,不确定其他版本。

关于python - 通过 API 与 Jupyter Notebooks 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54475896/

相关文章:

python - 从 Pivot reshape 和选择 Pandas

python - 在笔记本中导入 Polars 会导致内核崩溃

python - 是否可以将一个单元格从一个 jupyter 笔记本复制到另一个?

python - jupyter nbconvert --to html --no-inp 正在缩小集中表的显示

jupyter-notebook - 如何将Jupyter/IPython笔记本转换为LaTex?

python - 为什么 Jupyter 在通过 Conda 安装时会降级 Tensorflow?

python - 如何构建一个 GUI 以在 jupyter notebook 中使用?

python - 无法从 python 2.7 中的 x 导入名称

Python 写入空的 json 文件

python - numpy.asarray : how to check up that its result dtype is numeric?