OK, I found a solution:

%%javascript
var nb = Jupyter.notebook;
var port = window.location.port;
nb.kernel.execute("NB_Port = '" + port + "'");


The above code will put the port (in string form) into the IPython variable 
NB_Port. I can then use it to build the correct URL to get the path to the 
current notebook, like this:

# Get file path of this notebook
connection_file_path = kernel.get_connection_file()
connection_file = os.path.basename(connection_file_path)
kernel_id = connection_file.split('-', 1)[1].split('.')[0]
sessions = json.load(urllib2.urlopen('http://127.0.0.1:'+NB_Port+
'/api/sessions'))
for sess in sessions:
    if sess['kernel']['id'] == kernel_id:
        nb_rel_path = (sess['notebook']['path'])
        break
res = !echo ~
nb_path = os.path.join(res[0],nb_rel_path)
nb_path
nb_dir,nb_filename = os.path.split(nb_path)


This now works even as I have two Jupyter notebook sessions open,  one 
running Python 2.7 and one Python 3.6.Thanks to Johannes for showing me 
this method. 
Now, if I could find a way that works on Windows as well....

It's a shame that we have to do this.

-- 
You received this message because you are subscribed to the Google Groups 
"Project Jupyter" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/jupyter/fbe99aef-31dc-460c-8b4f-0af59d2aeb3c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to