如何解决 ModuleNotFound 错误:VSCode Python 3.10.0 中没有名为“stuff”的模块

问题描述 投票:0回答:1

我创建了一个名为 stuff 的模块,并在 stuff 文件夹中创建了这些文件,visual studio code preview

__init__.py
accum.py

accum.py
我有

class Accumulator:

    def __init__(self):
        self._count = 0
    
    @property
    def count(self):
        return self._count
        
    def add(self, more=1):
        self._count += more

我创建了一个新文件夹

test
,并在
test
文件夹中创建了一个文件
test_accum.py

在我有的

test_accum.py
文件中

import pytest

from stuff.accum import Accumulator

当我运行 Python 文件时,它返回:

ModuleNotFoundError: No module named 'stuff'
python visual-studio-code pytest
1个回答
1
投票

如果您尝试运行测试模块,它会失败,因为它不在 @tromgy 解释的路径中。但是,要运行测试,您不需要初始化文件或弄乱

sys.path

使用 pytest,您不应该运行测试模块本身来运行测试,而是使用

python -m pytest tests
从命令行运行 pytest。只需确保您正在从项目文件夹运行,即“tau-intro-to-pytest”。如果您想运行特定的测试函数,您也可以从命令行指定,但是有很好的 VS Code 扩展可以做到这一点,而无需编写冗长的命令行调用。 python 扩展包含一个测试资源管理器,但我更喜欢 Python Test Explorer for VS Code 的 UI。

© www.soinside.com 2019 - 2024. All rights reserved.