我有一个Python(2.7)项目,其中包含我自己的软件包util和operator(依此类推)。

我读了关于relative imports的信息,但也许我听不懂。我有以下目录结构:

top-dir/
  util/__init__.py (empty)
  util/ua.py
  util/ub.py
  operator/__init__.py
   ...

  test/test1.py


test1.py文件包含

#!/usr/bin/env python2
from __future__ import absolute_import # removing this line dosn't change anything. It's default functionality in python2.7 I guess
import numpy as np


当我在test1.py文件夹中执行test/时很好。但是,当我移到top-dir/时,import numpy想要包括我自己的util软件包:

Traceback (most recent call last):
  File "tests/laplace_2d_square.py", line 4, in <module>
    import numpy as np
  File "/usr/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
    import add_newdocs
  File "/usr/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
    from numpy.lib import add_newdoc
  File "/usr/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
    from type_check import *
  File "/usr/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
    import numpy.core.numeric as _nx
  File "/usr/lib/python2.7/site-packages/numpy/core/__init__.py", line 45, in <module>
    from numpy.testing import Tester
  File "/usr/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
    from unittest import TestCase
  File "/usr/lib/python2.7/unittest/__init__.py", line 58, in <module>
    from .result import TestResult
  File "/usr/lib/python2.7/unittest/result.py", line 9, in <module>
    from . import util
  File "/usr/lib/python2.7/unittest/util.py", line 2, in <module>
    from collections import namedtuple, OrderedDict
  File "/usr/lib/python2.7/collections.py", line 9, in <module>
    from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name itemgetter


麻烦的是

    from . import util


也许

    from operator import itemgetter as _itemgetter, eq as _eq


我能做什么?

最佳答案

operator是Python标准库中的模块。为您的模块提供与标准模块相同的名称会带来麻烦,应避免使用。

如果您绝对需要解决此问题的方法,则可以尝试使用sys.path变量。第一个元素通常是脚本的目录,或者是将导入系统定向到当前目录的空字符串。

oldpath = sys.path.pop(0)
import numpy
sys.path.insert(0, oldpath)

关于python - “import numpy”尝试加载我自己的包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17361096/

10-11 23:02