如何在.py文件中使用python代码在jupyter notebpook中查找文档名称

我想通过在python文件中编写代码来获取在Jupyter中创建的笔记本的文件名,并将其导入笔记本中,然后单击“运行”。这应该给我一个可以打印的变量中的文件名。

假设Jupyter中的笔记本名称是Get_File_Name.ipynb,所以我想将Get_File_Name存储在变量中。

尝试从文件中的python代码中使用javascript魔术单元,然后将该python文件导入笔记本。

尝试使用小部件在小部件中插入文件名。两者都不起作用

在文件print_filename.py中写入python代码


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)

在Jupyter笔记本中运行

import print_filename

如果我在另一段中打印nb_name,则可以获取它。但在同一段中,错误是 但是错误来了:

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)

相同的错误。

hail1999 回答:如何在.py文件中使用python代码在jupyter notebpook中查找文档名称

您可以使用https://github.com/AaronWatters/jp_proxy_widget

这是代码

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

这是屏幕截图:

enter image description here

本文链接:https://www.f2er.com/3154748.html

大家都在问