无法从不同目录导入 python 文件
Unable to import python file from different directory
我有以下文件夹层次结构。
apriltag
python
apriltag.py
my_notebook.ipynb
我只是想将 apriltag.py 导入到我的 Jupyter Notebook 中。我试过这样做..
import sys
import os.path
sys.path.append(os.path.dirname(os.path.realpath('__file__')) + "/apriltag/python")
import apriltag
但是,当我尝试从 apriltag
访问 class 时,如下所示:
print(apriltag.Detector)
我收到以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-74-d1254ec9a372> in <module>()
12 import apriltag
13
---> 14 print(apriltag.Detector)
AttributeError: module 'apriltag' has no attribute 'Detector'
提示模块导入不正确。我也尝试在 python
目录的根目录下创建 __init__.py
,但同样的事情发生了。
好的,我会早点过来。我可能会解决您的问题。如果我不这样做,我们可以回去解决它。
您可能已经看到,docs 说
The directory containing the script being run is placed at the beginning of the search path,
现在,您是 运行 my_notebook.ipynb,因此它的目录是搜索路径的最开始。您可能在同一级别的 apriltag 目录中有一个 __init__.py
文件。因此,它作为一个模块被发现并加载。 "module" 中没有 .py 文件,你的 __init__.py
中也没有任何文件,所以它作为一个空模块加载。
相反,不要尝试修改 sys.path 目录,只需在 apriltag 和 python 目录中创建空的 __init__.py
文件即可。
然后,您应该可以执行以下操作:
from apriltag.python import apriltag
导入的 apriltag 应该就是您需要的那个。 (而且 dir(apriltag)
会给你更好的结果。)
一般来说,我总是将我的所有代码设置在空 __init__.py
的目录中,并使用 from
语法调用它们。它使模块更容易处理。
我有以下文件夹层次结构。
apriltag
python
apriltag.py
my_notebook.ipynb
我只是想将 apriltag.py 导入到我的 Jupyter Notebook 中。我试过这样做..
import sys
import os.path
sys.path.append(os.path.dirname(os.path.realpath('__file__')) + "/apriltag/python")
import apriltag
但是,当我尝试从 apriltag
访问 class 时,如下所示:
print(apriltag.Detector)
我收到以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-74-d1254ec9a372> in <module>()
12 import apriltag
13
---> 14 print(apriltag.Detector)
AttributeError: module 'apriltag' has no attribute 'Detector'
提示模块导入不正确。我也尝试在 python
目录的根目录下创建 __init__.py
,但同样的事情发生了。
好的,我会早点过来。我可能会解决您的问题。如果我不这样做,我们可以回去解决它。
您可能已经看到,docs 说
The directory containing the script being run is placed at the beginning of the search path,
现在,您是 运行 my_notebook.ipynb,因此它的目录是搜索路径的最开始。您可能在同一级别的 apriltag 目录中有一个 __init__.py
文件。因此,它作为一个模块被发现并加载。 "module" 中没有 .py 文件,你的 __init__.py
中也没有任何文件,所以它作为一个空模块加载。
相反,不要尝试修改 sys.path 目录,只需在 apriltag 和 python 目录中创建空的 __init__.py
文件即可。
然后,您应该可以执行以下操作:
from apriltag.python import apriltag
导入的 apriltag 应该就是您需要的那个。 (而且 dir(apriltag)
会给你更好的结果。)
一般来说,我总是将我的所有代码设置在空 __init__.py
的目录中,并使用 from
语法调用它们。它使模块更容易处理。