通过API与Jupyter笔记本电脑互动

问题描述 投票:3回答:2

问题:我想从通过Jupyter API其他应用程序与Jupyter互动,特别是我想从应用程序至少(完美的变种对我来说是在运行之前编辑一些段落)运行我的笔记本电脑。我读过API documentation但还没有找到我需要什么。

我已经用于具有相同的结构(笔记本电脑和段落),其目的Apache Zeppelin

难道我刚才描述的使用Jupyter为目的人?

python jupyter-notebook jupyter remote-access apache-zeppelin
2个回答
4
投票

如果忽略使用Jupyter API的是对这个问题的最佳解决方案(在这个问题没有明确说明),下面的代码做了你问什么:它会远程执行Jupyter笔记本通过HTTP,并得到了一定的成果。它不是生产做好准备,它更多的是如何工作的一个示例。没有与产生大量输出单元测试 - 认为这将需要调整。

您还可以更改/通过改变代码编程阵列编辑代码。

您将需要更改notebook_path,底座和头部根据您的配置,看代码的细节。

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作为传输。

作为参考这一点也适用笔记本5.7.4,不清楚其他版本。


1
投票

我认为,使用远程Jupyter笔记本是过度设计你的情况。

我看到的好办法是通过必要的参数Python程序利用测井。

© www.soinside.com 2019 - 2024. All rights reserved.