Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过API与Jupyter笔记本互动_Python_Jupyter Notebook_Jupyter_Remote Access_Apache Zeppelin - Fatal编程技术网

Python 通过API与Jupyter笔记本互动

Python 通过API与Jupyter笔记本互动,python,jupyter-notebook,jupyter,remote-access,apache-zeppelin,Python,Jupyter Notebook,Jupyter,Remote Access,Apache Zeppelin,问题是:我想通过Jupyter API与另一个应用程序中的Jupyter进行交互,尤其是我想至少从应用程序中运行我的笔记本(对我来说,完美的变体是在运行之前编辑一些段落)。我读了这本书,但还没有找到我需要的东西 我使用了相同结构的笔记本和段落 有人使用Jupyter达到我刚才描述的目的吗?我认为,在你的情况下,使用远程Jupyter笔记本是过度工程化的 我认为最好的方法是通过测井将必要的参数传递给python程序。忽略如果使用Jupyter API是解决问题的最佳解决方案(问题中没有明确描述),

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

我使用了相同结构的笔记本和段落


有人使用Jupyter达到我刚才描述的目的吗?

我认为,在你的情况下,使用远程Jupyter笔记本是过度工程化的


我认为最好的方法是通过测井将必要的参数传递给python程序。

忽略如果使用Jupyter API是解决问题的最佳解决方案(问题中没有明确描述),下面的代码会满足您的要求:它将通过http远程执行Jupyter笔记本并获得一些结果。它还没有准备好生产,它更多的是一个如何做到这一点的例子。没有用能产生大量输出的电池进行测试-认为需要调整

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

您需要根据您的配置更改笔记本路径、底部和标题,有关详细信息,请参阅代码

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()
此代码所基于的有用链接(如果您需要更多信息,我建议您阅读):

注意,也有,但据我所知,它不支持HTTP作为传输


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

我没有足够的声誉发表评论,但(对我来说)如果笔记本中有降价单元格,接受的答案将失败(卡在无限循环中)。调整代码

code = [ c['source'] for c in file['content']['cells'] if len(c['source'])>0 ]


为我修复了这个问题

你可能想看看其中的一个项目,因为那些libs/插件正是这样做的:或者。我希望这有帮助。伟大的代码片段!作为简要说明,如果您不想检查控制台输出以查找jupyter令牌是什么,您可以在启动笔记本时手动指定令牌,使用如下环境变量:
$jupyter\u token=这是我的令牌jupyter笔记本
当我尝试此操作时,
而msg\u type!=“stream”
似乎是一个无限循环。但是,我可以看到类型为
execute\u reply
的消息,但这些消息中似乎没有代码输出。你知道为什么会出现这种情况吗?你为什么要附加-/api/kernels,如果我附加了/api/kernels部分,我就可以从基本URL在浏览器上访问我的笔记本,但找不到任何页面。@Infinite:也许可以提一下你使用的笔记本的版本。答案大约是2年前的,在答案中提到的版本(5.7.4)和今天大约有20个新版本之间-事情可能已经改变了。
code = [ c['source'] for c in file['content']['cells'] if len(c['source'])>0 and c['cell_type']=='code' ]