如何获取当前的IPython Notebook名称 [英] How do I get the current IPython Notebook name

查看:127
本文介绍了如何获取当前的IPython Notebook名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to obtain the current NoteBook name when running the IPython notebook. I know I can see it at the top of the notebook. What I am after something like

currentNotebook = IPython.foo.bar.notebookname()

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

I need to get the name in a variable.

推荐答案

正如已经提到的,你可能不应该真的能够做到这一点,但我确实找到了办法。这是一个火热的黑客,所以不要依赖这个:

As already mentioned you probably aren't really supposed to be able to do this, but I did find a way. It's a flaming hack though so don't rely on this at all:

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中工作的解决方案至少通过一个简单的测试。如果有多个笔记本连接到同一个内核等,可能无法保证给出正确的答案。

I updated my answer to include a solution that "works" in IPython 2.0 at least with a simple test. It probably isn't guaranteed to give the correct answer if there are multiple notebooks connected to the same kernel, etc.

这篇关于如何获取当前的IPython Notebook名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆