Ask Your Question

Access notebook filename from jupyter with sagemath kernel

asked 2017-03-09 10:22:04 +0200

Say I am running sage in a jupyter notebook, e.g. invoked with sage -n jupyter my_nootebook_file.ipynb. After some computations I want to call a function from a custom library that stores all data in a file named

I can do all the above manually, but I want the function to know that it is run inside the my_nootebook_file.ipynb notebook and hence the canonical output filename should be my_nootebook_file.*. How can I access this information? Shouldn't there be a "process information object" that should have all this information like current directory, ? I cannot seem to find it.

I did try

def outp(L):
    print [str(l) for l in L]

and searched the output for my notebook name, to no avail. Any hints are more than welcome.

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted

answered 2017-03-10 07:27:36 +0200

mforets gravatar image

updated 2017-03-10 07:33:38 +0200

To add another possibility to the list,

var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook = " + "'"+thename+"'";

and print(theNotebook) in a subsequent code cell produces the name of your notebook.

If you are working in a notebook and change its name, the code containing the javascript magic has to be executed for theNotebook variable to be updated.

Source: How to I get the current IPython Notebook name.

edit flag offensive delete link more


+1 for this interesting approach. While it does return the notebook name, it seems to me I cannot include the javascript code into a function that I can externalize into a library/module and thus make it available as a function, like get_notebook_name() or so. That is really what I am looking for in my use case.

Björn gravatar imageBjörn ( 2017-03-10 14:15:12 +0200 )edit

answered 2017-03-10 01:09:21 +0200

vdelecroix gravatar image

To get the full path of the current directory you can use the os Python module as follows

sage: import os
sage: os.path.abspath(os.curdir)

However, there is no such thing such as a Python environment variable to tell you the name of the current worksheet (that I know of). This woud be much simpler within a Python script.

edit flag offensive delete link more


I agree. Python knows sys.argv[0]. I need the equivalent for jupyter notebooks running sagemath.

Björn gravatar imageBjörn ( 2017-03-10 14:17:28 +0200 )edit

Interestingly, if I run jupyter with a python kernel, sys.argv does not contain the name of the notebook either. But then, the python notebook is not a "script".

Björn gravatar imageBjörn ( 2017-03-10 14:22:20 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-03-09 10:22:04 +0200

Seen: 3,462 times

Last updated: Mar 10 '17