Python“导入错误:没有名为模块”问题

2024-02-26

我在 Windows XP SP3 上运行 Python 2.6.1。我的 IDE 是 PyCharm 1.0-Beta 2 版本 PY-96.1055。

我将 .py 文件存储在名为“src”的目录中;它有一个__init__.py除“之外的空文件”__author__” 属性位于顶部。

其中之一称为 Matrix.py:

#!/usr/bin/env python
"""
"Core Python Programming" chapter 6.
A simple Matrix class that allows addition and multiplication
"""
__author__ = 'Michael'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"

class Matrix(object):
    """
    exercise 6.16: MxN matrix addition and multiplication
    """
    def __init__(self, rows, cols, values = []):
        self.rows = rows
        self.cols = cols
        self.matrix = values

    def show(self):
        """ display matrix"""
        print '['
        for i in range(0, self.rows):
            print '(',
            for j in range(0, self.cols-1):
                print self.matrix[i][j], ',',
            print self.matrix[i][self.cols-1], ')'
        print ']'

    def get(self, row, col):
        return self.matrix[row][col]

    def set(self, row, col, value):
        self.matrix[row][col] = value

    def rows(self):
        return self.rows

    def cols(self):
        return self.cols

    def add(self, other):
        result = []
        for i in range(0, self.rows):
            row = []
            for j in range(0, self.cols):
                row.append(self.matrix[i][j] + other.get(i, j))
            result.append(row)
        return Matrix(self.rows, self.cols, result)

    def mul(self, other):
        result = []
        for i in range(0, self.rows):
            row = []
            for j in range(0, other.cols):
                sum = 0
                for k in range(0, self.cols):
                    sum += self.matrix[i][k]*other.get(k,j)
                row.append(sum)
            result.append(row)
        return Matrix(self.rows, other.cols, result)

    def __cmp__(self, other):
        """
        deep equals between two matricies
        first check rows, then cols, then values
        """
        if self.rows != other.rows:
            return self.rows.cmp(other.rows)
        if self.cols != other.cols:
            return self.cols.cmp(other.cols)
        for i in range(0, self.rows):
            for j in range(0, self.cols):
                if self.matrix[i][j] != other.get(i,j):
                    return self.matrix[i][j] == (other.get(i,j))
        return True # if you get here, it means size and values are equal



if __name__ == '__main__':
    a = Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    b = Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
    c = Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
    a.show()
    b.show()
    c.show()
    a.add(b).show()
    a.mul(c).show()

我创建了一个名为“test”的新目录,其中还有一个__init__.py除“之外的空文件”__author__“属性位于顶部。我创建了一个 MatrixTest.py 来组合我的 Matrix 类:

#!/usr/bin/env python
"""
Unit test case for Matrix class
See http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting for Python coding guidelines
"""

import unittest #use my unittestfp instead for floating point
from src import Matrix # Matrix class to be tested

__author__ = 'Michael'
__credits__ = []
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"

class MatrixTest(unittest.TestCase):
    """Unit tests for Matrix class"""
    def setUp(self):
        self.a = Matrix.Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        self.b = Matrix.Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
        self.c = Matrix.Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])

    def testAdd(self):
        expected = Matrix.Matrix(3, 3, [[7, 7, 7], [5, 6, 7], [9, 9, 9]])    # need to learn how to write equals for Matrix
        self.a.add(self.b)
        assert self.a == expected

if __name__ == '__main__':    #run tests if called from command-line
    suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
    unittest.TextTestRunner(verbosity=2).run(suite)

然而,当我尝试运行 MatrixTest 时,出现此错误:

C:\Tools\Python-2.6.1\python.exe "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py"
Traceback (most recent call last):
  File "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py", line 8, in <module>
    from src import Matrix # Matrix class to be tested
ImportError: No module named src

Process finished with exit code 1

我读过的所有内容都告诉我,拥有init我所有目录中的 .py 应该处理这个问题。

如果有人能指出我错过了什么,我将不胜感激。

我还想了解有关开发和维护源代码和单元测试类的最佳方法的建议。我以编写 Java 时通常的方式思考这个问题:/src 和 /test 目录,下面具有相同的包结构。这是“Pythonic”思维,还是我应该考虑另一种组织方案?

UPDATE:

感谢那些回答的人,这是对我有用的解决方案:

  1. 将导入更改为from src import Matrix # Matrix class to be tested
  2. Add sys.path作为我的unittest配置的环境变量,./src和./test目录用分号分隔。
  3. 更改 MatrixTest.py 中的声明,如图所示。

这是一个猜测,但我认为你需要改变你的 PYTHONPATH http://docs.python.org/using/windows.html#excursus-setting-environment-variables环境变量以包含 src 和 test 目录。

运行程序在src目录可能已经工作,因为Python自动插入当前正在运行的脚本的目录sys.path。所以导入模块src只要您还执行驻留在中的脚本,就会起作用src.

但现在你正在运行一个脚本test, the test目录会自动添加到sys.path, while src is not.

PYTHONPATH 中列出的所有目录都会添加到sys.path,以及 Python 搜索sys.path来查找模块。

另外,如果你说

from src import Matrix

then Matrix会提到包裹,你需要说Matrix.Matrix访问班级。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python“导入错误:没有名为模块”问题 的相关文章

随机推荐