此代码在Ipython / Juypter单元格中正常工作以获取笔记本文件名:
js = """var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook2 = " + "'"+thename+"'";
kernel.execute(command);"""
display(Javascript(js))
theNotebook2 + '.ipynb'
'techela.ipynb'
如果我在单元格中定义一个函数并调用它:
def get_filename():
"""Get the notebook filename."""
js = """var kernel = IPython.notebook.kernel;
var thename = window.document.getElementById("notebook_name").innerHTML;
var command = "theNotebook2 = " + "'"+thename+"'";
kernel.execute(command);"""
display(Javascript(js))
return theNotebook2 + '.ipynb'
get_filename()
'techela.ipynb'
它似乎工作正常,并给我文件名。
但是,如果我将该功能放入模块中并导入它,那么它就会停止工作。
from techela import get_filename
get_filename()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-42ee37d0d253> in <module>()
1 from techela import get_filename
----> 2 get_filename()
/Users/jkitchin/techela/ipynb/techela.py in get_filename()
11 kernel.execute(command);"""
12 display(Javascript(js))
---> 13 return theNotebook2 + '.ipynb'
14
15
NameError: name 'theNotebook2' is not defined
知道为什么会失败吗?