我有这样的文件夹结构
root/
A0/
A1/
B0/
B1/
可以说我有一个名为test.py的文件。在其中,我像这样导入numpy
import numpy as np
这就是文件中包含的所有内容。当它位于子文件夹A0,A1,B0的根目录中时,它可以正常工作,但会在子文件夹B1中引发错误。是否引发错误如下:
Traceback (most recent call last):
File "pose/utils/test.py", line 1, in <module>
import numpy as np
File "/home/adrian/.local/lib/python3.6/site-packages/numpy/__init__.py", line 187, in <module>
from .testing import Tester
File "/home/adrian/.local/lib/python3.6/site-packages/numpy/testing/__init__.py", line 10, in <module>
from unittest import TestCase
File "/usr/lib/python3.6/unittest/__init__.py", line 59, in <module>
from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf,
File "/usr/lib/python3.6/unittest/case.py", line 6, in <module>
import logging
File "/home/adrian/Projects/lpr-pose-estimation/pose/utils/logging.py", line 3, in <module>
from pose.utils.utils import mkdir_if_missing
File "/home/adrian/Projects/lpr-pose-estimation/pose/utils/utils.py", line 4, in <module>
from scipy.misc import imresize
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/misc/__init__.py", line 68, in <module>
from scipy.interpolate._pade import pade as _pade
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/interpolate/__init__.py", line 175, in <module>
from .interpolate import *
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py", line 32, in <module>
from .interpnd import _ndim_coords_from_arrays
File "interpnd.pyx", line 1, in init scipy.interpolate.interpnd
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/spatial/__init__.py", line 98, in <module>
from .kdtree import *
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/spatial/kdtree.py", line 8, in <module>
import scipy.sparse
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/sparse/__init__.py", line 230, in <module>
from .base import *
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/sparse/base.py", line 9, in <module>
from scipy._lib._numpy_compat import broadcast_to
File "/home/adrian/.local/lib/python3.6/site-packages/scipy/_lib/_numpy_compat.py", line 16, in <module>
_assert_warns = np.testing.assert_warns
AttributeError: module 'numpy' has no attribute 'testing'
导入为模块(例如cv2)也会导致错误,但只能将其导入numpy:
ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
File "pose/utils/test.py", line 1, in <module>
import cv2 as cv
File "/home/adrian/.local/lib/python3.6/site-packages/cv2/__init__.py", line 3, in <module>
from .cv2 import *
ImportError: numpy.core.multiarray failed to import
这种错误可能是什么原因?
答案 0 :(得分:0)
如果您的启动脚本位于.../pose/utils
中,则每个绝对导入都将在其中查找模块。该目录包含一个名为logging
的模块(类似于标准库中的模块)。
在numpy
程序包初始化期间(执行其__init__.py
),并且在numpy.testing
可用之前,通常会发生导入链(如回溯所示),这导致错误的logging
模块会导致导入_numpy_compat
,而该模块试图过早访问numpy.testing
。
为避免此循环导入问题,您可以重命名logging
模块或将启动脚本移动到另一个目录。