我如何获得当前的IPython Notebook名称?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (68)

我试图在运行IPython笔记本时获取当前的NoteBook名称。我知道我可以在笔记本顶部看到它。

currentNotebook = IPython.foo.bar.notebookname()

我需要在变量中获取名称。

提问于
用户回答回答于
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
用户回答回答于

NOTEBOOK_FULL_PATH在当前笔记本前端存储:

%%javascript
var nb = IPython.notebook;
var kernel = IPython.notebook.kernel;
var command = "NOTEBOOK_FULL_PATH = '" + nb.base_url + nb.notebook_path + "'";
kernel.execute(command);

然后显示它:

print("NOTEBOOK_FULL_PATH:\n", NOTEBOOK_FULL_PATH)

运行第一个Javascript单元格不会产生输出。运行第二个Python单元格产生如下内容:

NOTEBOOK_FULL_PATH:
 /user/zeph/GetNotebookName.ipynb

扫码关注云+社区

领取腾讯云代金券