如何使用python 3.75从子包相对导入到顶级文件夹workdirectory?

2024-04-25 19:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

Project_folder
│
├───Tests
│   │   __init__.py
│   │
│   │
│   ├───features
│   │       smallcircle.feature
│   │
│   ├───steps_tests
│   │   │   test_smallcircle.py
│   │   │   __init__.py
│   __init__.py
│   a.py

我正在尝试从test\u smallcircle.pya.py进行相对导入,如下所示

import sys
import os
sys.path.append(os.path.dirname("C:\\Users\\Manuel\\Desktop\\solution\\a.py"))
from a import smallest_circle # JUST HERE
from pytest_bdd import (
    given,
    scenario,
    then,
    when,
)
import pytest_bdd
from functools import partial

但它显示了下一个错误

Unable to import 'a'

2条回答

我发现了错误,它位于absulte路径C:\\Users\\Manuel\\Desktop\\solution\\a.py 当我附加到sys.path变量后,绝对路径应该是目录,而不是目标文件,因此解决方案是将其替换为C:\\Users\\Manuel\\Desktop\\solution

如果需要相对导入,则需要提升一个级别:

from ..a import smallest_circle

相关问题 更多 >