CHR*_*HRD 13 python relative-import anaconda jupyter-notebook
假设我有以下结构:
\n\n dir_1\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 functions.py\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 dir_2\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 code.ipynb\n
Run Code Online (Sandbox Code Playgroud)\n\n在,,code.ipynb
我只是想访问里面的一个函数functions.py
并尝试了这个:
from ..functions import some_function\n
Run Code Online (Sandbox Code Playgroud)\n\n我收到错误:
\n\nattempted relative import with no known parent package\n
Run Code Online (Sandbox Code Playgroud)\n\n我已经检查了一堆类似的帖子,但还没有弄清楚这一点...我正在从 a 运行 jupyter 笔记本,conda env
我的 python 版本是3.7.6
.
在你的笔记本中执行以下操作:
import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function
Run Code Online (Sandbox Code Playgroud)
jupyter 笔记本从 sys.path 中的当前工作目录开始。请参阅系统路径
...包含用于调用 Python 解释器的脚本的目录。
如果您的实用程序函数位于父目录中,您可以执行以下操作:
import os, sys
parent_dir = os.path.abspath('..')
# the parent_dir could already be there if the kernel was not restarted,
# and we run this cell again
if parent_dir not in sys.path:
sys.path.append(parent_dir)
from functions import some_function
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7741 次 |
最近记录: |