您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何获取当前的IPython / Jupyter Notebook名称

如何获取当前的IPython / Jupyter Notebook名称

如前所述,您可能真的不应该能够执行此操作,但是我确实找到了一种方法。尽管这是一个令人发指的骇客,所以请不要完全依赖于此:

import json
import os
import urllib2
import IPython
from IPython.lib import kernel
connection_file_path = kernel.get_connection_file()
connection_file = os.path.basename(connection_file_path)
kernel_id = connection_file.split('-', 1)[1].split('.')[0]

# Updated answer with semi-solutions for both IPython 2.x and IPython < 2.x
if IPython.version_info[0] < 2:
    ## Not sure if it's even possible to get the port for the
    ## notebook app; so just using the default...
    notebooks = json.load(urllib2.urlopen('http://127.0.0.1:8888/notebooks'))
    for nb in notebooks:
        if nb['kernel_id'] == kernel_id:
            print nb['name']
            break
else:
    sessions = json.load(urllib2.urlopen('http://127.0.0.1:8888/api/sessions'))
    for sess in sessions:
        if sess['kernel']['id'] == kernel_id:
            print sess['notebook']['name']
            break

我更新了答案,以包含至少在一个简单的测试中即可在IPython 2.0中“运行”的解决方案。如果有多个笔记本连接到同一内核等,则可能无法保证给出正确的答案。

python 2022/1/1 18:42:11 有286人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶