VS代码python错误找不到导入的文件

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

所以我正在使用 python,并且我有以下文件架构:

- 10.Testing (parent folder)
  -- files (folder)
    |__  __init__.py (empty file)
    |__simple_functions.py
  -- tests (folder)
    |__ test_simple_functions.py
    |__  __init__.py (empty file)

10.Testing:这是我的父文件夹,其中包含2个文件夹,测试和文件。 文件:这是我的父文件夹中的子文件夹。它包含 Python 文件

simple_functions.py
,我在其中定义了一些函数。 测试:这是我的父文件夹中的另一个子文件夹。它包含 Python 文件
test_simple_functions.py
,我正在其中为 simple_functions.py 中的函数编写测试用例。

澄清一下,我并不是 100% 确信这应该是存储库的文件结构。如果没有请告诉。

test_simple_functions.py
中我添加了以下代码:

# testing the file simple_functions.py

from files.simple_functions import *



def main():
    squared_function(2)





if __name__ == '__main__':
    main()



所以我正在使用 VS Code 并尝试执行

simple_functions.py
的代码,但我不能它说:

回溯(最近一次调用最后一次):文件 “ ests est_simple_functions.py”,第 3 行,在 从 files.simple_functions 导入 *

例如来自工作区文件夹:

py tests/test_simpl_functions.py

来自测试文件夹:

tests> py .\test_simple_functions.py

无论我在哪里运行文件: 无论我在测试文件夹、工作区文件夹、文件文件夹中,它都不起作用。

但是在我的

test_simple_functions.py

我的工作区/exporer 说父文件 10.Testing 我尝试了终端 bash 、 powershell 和 cmd 。

它以浅蓝色/绿色突出显示“files.simple_function”(不确定颜色哈哈),VS代码识别出那里有函数,我可以使用它们并使用它们来自动完成,那么问题是什么?

我应该做什么?

这是最好的做法吗?

我尝试在多个文件夹中运行代码并测试它不起作用但在 vs code 中识别它的代码

python visual-studio visual-studio-code testing import
1个回答
0
投票

你的目录是这样的:

Testing/                           # Parent folder
│
├── files/                            # Subfolder for Python modules
│   ├── __init__.py                   # Makes files a Python package
│   └── simple_functions.py           # Python file with function definitions
│
└── tests/                            # Subfolder for tests
    ├── __init__.py                   # Makes tests a Python package
    └── test_simple_functions.py      # Test cases for simple_functions.py

  1. 运行
    test_simple_functions.py
    以便它看到
    tests
    包,将
    cd
    放入
    Testing
    并像这样运行:
python -m tests.test_simple_functions

这样,python 就能看到这两个包。

  1. 在您希望运行的代码中,您可以通过添加以下内容来要求 python 监视父目录:
import sys
sys.path.append('..')  # Adds the parent directory to python path

注意:这必须在您导入之前进行。

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