首页 > 解决方案 > 如何使用 python 3.75 从子包到顶级文件夹工作目录的相对导入?

问题描述

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

我正在尝试从test_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'

标签: pythonimportrelative-import

解决方案


如果你想要一个相对导入,你需要上一个级别:

from ..a import smallest_circle

推荐阅读