Py之jupyter_client:jupyter_client的简介、安装、使用方法之详细攻略

Py之jupyter_client:jupyter_client的简介、安装、使用方法之详细攻略

目录

jupyter_client的简介

jupyter_client的安装

jupyter_client的使用方法

1、基础用法

(1)、获取内核信息

(2)、执行代码块

(3)、远程执行代码


jupyter_client的简介

jupyter_client 包含 Jupyter 协议的参考实现。它还提供了用于与内核交互的客户端和内核管理 API。此外,它还提供了用于在 Jupyter 前端安装内核规范 (kernelspecs) 的 jupyter kernelspec 入口点。

jupyter_client 是与 Jupyter 交互式计算环境通信的 Python 库。Jupyter 是一个开源项目,支持交互式计算和可视化的工具,主要包括 Jupyter Notebook、Jupyter Lab 等。jupyter_client 是 Jupyter 中的一个关键组件,它允许不同的 Jupyter 组件(例如笔记本、内核)之间进行通信。主要功能包括:

>> 内核连接: 允许 Jupyter 笔记本与后台计算内核(例如 Python、R、Julia 等)建立连接。这使得笔记本可以发送代码块给内核执行,并接收执行结果。

>> 消息传递: 提供了 Jupyter 协议规范中定义的消息传递机制。这些消息包括执行代码、获取输出、传递错误等。jupyter_client 负责在 Jupyter 组件之间传递这些消息。

>> 会话管理: 管理与内核之间的交互会话,包括启动和关闭内核,以及与内核之间的通信。

jupyter_client 是 Jupyter 生态系统的一部分,而且由于其提供了一个通用的消息传递框架,也可以被其他工具和库用于构建与 Jupyter 类似的交互式计算环境。这使得开发者能够创建支持 Jupyter 协议的客户端和服务,以进行交互式计算。

GitHub地址GitHub - jupyter/jupyter_client: Jupyter protocol client APIs

文档地址Jupyter Client 8.6 — jupyter_client 8.6.0 documentation

jupyter_client的安装

如果你使用 Jupyter 笔记本或其他 Jupyter 相关的工具,jupyter_client 库通常是作为依赖项被安装的。

pip install jupyter-client

jupyter_client的使用方法

1、基础用法

(1)、获取内核信息

from jupyter_client import kernelspec

# 获取内核规范信息
specs = kernelspec.get_all_specs()
print(specs)

(2)、执行代码块

from jupyter_client import BlockingKernelClient

# 创建 BlockingKernelClient
kc = BlockingKernelClient()
kc.start_channels()

# 执行代码块
code = "print('Hello, Jupyter!')"
msg_id = kc.execute(code)

# 等待执行结果
reply = kc.get_shell_msg(timeout=10)
content = reply['content']

# 打印结果
print(content['text'])

(3)、远程执行代码

from jupyter_client import BlockingKernelClient
from jupyter_client.localinterfaces import public_ips

# 创建 BlockingKernelClient
kc = BlockingKernelClient()
kc.start_channels()

# 获取公共 IP 地址
public_ip = public_ips()[0]

# 执行代码块
code = "print('Hello, Remote Jupyter!')"
msg_id = kc.execute(code, allow_stdin=False, store_history=False, silent=False)

# 等待执行结果
reply = kc.get_shell_msg(timeout=10)
content = reply['content']

# 打印结果
print(content['text'])

猜你喜欢

转载自blog.csdn.net/qq_41185868/article/details/134844449