Tooblippe Tooblippe - 1 year ago 416
Python Question

How to I get the current IPython Notebook name

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 =

I need to get the name in a variable.

Answer Source

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(''))
    for nb in notebooks:
        if nb['kernel_id'] == kernel_id:
            print nb['name']
    sessions = json.load(urllib2.urlopen(''))
    for sess in sessions:
        if sess['kernel']['id'] == kernel_id:
            print sess['notebook']['name']

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download