如何从该笔记本中访问Jupyter笔记本的名称
我想从该Juypyter笔记本中访问Jupyter笔记本的名称。 我需要这个名称,因为我想导入一个包含一些辅助代码的小.py
文件。此heatmap_axes.py
文件在笔记本上的文件夹外面。 So I am using an approach from here.这种方法要求我使用__文件__
访问当前文件的名称,但这似乎在Jupyter笔记本中不起作用。
那是代码:
script_dir = os.path.dirname(__file__)
module_dir = os.path.join(script_dir, '..')
sys.path.append(module_dir)
from heatmap_axes import set_date_ticks
当我运行代码时,我会收到一个错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2232/3919301704.py in <module>
21 from distutils.spawn import find_executable
22
---> 23 script_dir = os.path.dirname(__file__)
24 module_dir = os.path.join(script_dir, '..')
25 sys.path.append(module_dir)
NameError: name '__file__' is not defined
好的,我可以自己编写笔记本的名称,但是我需要在几个笔记本中导入此助手.py
文件。 ,所以我想要一个自动解决方案。使用笔记本在文件夹中复制.py
也不是一个选项代码>这些目录中的文件。
也就是说,文件结构的外观:
heatmap_axes.py
nb01\
<somenotebookname>.ipynb
...
nb02\
<somenotebookname>.ipynb
...
nb03\
...
I want to access the name of a jupyter notebook from within that juypyter notebook.
I need the name, because I want to import a small .py
file containing some helper code. This heatmap_axes.py
file is outside the folder, where the notebook is. So I am using an approach from here. This approach requires my to access the name of the current file with __file__
, but that doesn't seem to work in the jupyter notebook.
That is the code:
script_dir = os.path.dirname(__file__)
module_dir = os.path.join(script_dir, '..')
sys.path.append(module_dir)
from heatmap_axes import set_date_ticks
When I run the code, I get an error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2232/3919301704.py in <module>
21 from distutils.spawn import find_executable
22
---> 23 script_dir = os.path.dirname(__file__)
24 module_dir = os.path.join(script_dir, '..')
25 sys.path.append(module_dir)
NameError: name '__file__' is not defined
OK, I could write the name of the notebook on my own, but I need to import this helper .py
file in several notebooks, so I want an automated solution. Copying the .py
file inside the folder with the notebooks also is not an option, because I have many directories containg notebooks, and I don't want to have to copy this .py
file in each of these directories.
That is, what the file-structure looks like:
heatmap_axes.py
nb01\
<somenotebookname>.ipynb
...
nb02\
<somenotebookname>.ipynb
...
nb03\
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决:
找到。
Solved:
found here.
这在我基于 JupyterLab 的 Domo Jupyter 环境中对我有用:
This worked for me in my Domo Jupyter environment which is based on JupyterLab: