简体   繁体   English

如何使用 python 3.75 从子包到顶级文件夹工作目录的相对导入?

[英]how to do a relative import from subpackage to top folder workdirectory with python 3.75?

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

I'm triying to make a relative import from test_smallcircle.py to a.py as shown bellow我正在尝试从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

but it shows the next error但它显示下一个错误

Unable to import 'a'

If you want a relative import, you need to go up a level:如果要相对导入,则需要将 go 上一级:

from ..a import smallest_circle

I found the error, it was at the absulte path C:\\Users\\Manuel\\Desktop\\solution\\a.py that I append to the sys.path variable, the absolute path should be to the directory, not to the target file, so the solution was replacing it for C:\\Users\\Manuel\\Desktop\\solution我发现了错误,它在绝对路径C:\\Users\\Manuel\\Desktop\\solution\\a.py我 append 到 sys.path 变量,绝对路径应该是目录,而不是到目标文件,因此解决方案将其替换为C:\\Users\\Manuel\\Desktop\\solution

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM