1

I want to get the filename of the notebook created in Jupyter by writing code in a python file and import it in notebook and then click on Run. This should give me the name of file in a variable which I can print.

Suppose notebook name in Jupyter is Get_File_Name.ipynb So I want to store Get_File_Name in a variable.

Tried using javascript magic cell from python code in a file and import that python file in notebook.

Tried using widgets to insert filename in a widget. Both not working

Write python code in file print_filename.py


from IPython import get_ipython
ipython = get_ipython()

ipython.run_cell_magic('javascript', '','IPython.notebook.kernel.execute(\'nb_name = "\' + IPython.notebook.notebook_name + \'"\')')
print(nb_name)

In Jupyter notebook run the using

import print_filename

If I print nb_name in different paragraph, I am able to fetch it. But in same paragraph, error is But error comes:

NameError                                 Traceback (most recent call last)
<ipython-input-4-5fa7a942367b> in <module>
----> 1 import print_filename

~/print_filename.py in <module>
      2 ipython = get_ipython()
      3 ipython.run_cell_magic('javascript', '','IPython.notebook.kernel.execute(\'nb_name = "\' + IPython.notebook.notebook_name + \'"\')')
----> 4 print(nb_name)

NameError: name 'nb_name' is not defined```


Tried other way:

```python

from IPython import get_ipython
ipython = get_ipython()

ipython.run_cell_magic('javascript', '','IPython.notebook.kernel.execute(\'nb_name = "\' + IPython.notebook.notebook_name + \'"\')')

import print_filename
print(nb_name)

Same error.

1 Answer 1

0

You can do this using https://github.com/AaronWatters/jp_proxy_widget

Here is the code

import jp_proxy_widget

nb_name = None

def save_name(name):
    global nb_name
    nb_name = name

get_name = jp_proxy_widget.JSProxyWidget()
get_name.js_init("""
var name = IPython.notebook.notebook_name;
element.html("The name of the notebook is" + name);
save_name(name);
""", save_name=save_name)
get_name

Here is the screenshot:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.