Python导入失败,错误信息为ImportError: 尝试相对导入但没有已知的父包
我正在使用Python,下面是我的文件夹结构:
/new/uiautomation/testscripts/dropdown_test.py
/new/uiautomation/apis/runner.py
/new/apis/restapi.py
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
在我的dropdown_test.py文件里,它位于testscripts文件夹中,我想导入restapi.py和runner.py这两个文件,它们在不同的文件夹里。因为apis文件夹并不直接在testscripts的上面,所以我该怎么导入这两个模块,而不需要写死项目的文件夹名字(new)呢?我试过这样:
from apis.runner import Runner
from ..apis.restapi import Login
但是,这样并没有按预期工作。有没有办法在不指定项目文件夹名字的情况下,使用相对导入的方式呢?
唯一的问题是,我无法在testscripts/dropdown_test.py中找到或导入apis/restapi.py。
1 个回答
0
一般来说,我不太会回答那些几乎重复的问题。不过,应提问者的要求,我还是根据评论给出一个答案。
解决这个问题有几种方法。为了简单起见,我就提供一种,正如我在评论中提到的。
- 使用
sys.path.insert(0, ...)
注意这里使用了 .insert
,因为你希望这个路径是第一个被找到的,而不是最后一个。
- 再添加一个
os.path.dirname
,这样可以把你的sys.path
指向/new
。
然后,你可以使用:
import os
import sys
sys.path.insert(0, os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)))))
from uiautomation.apis.runner import Runner
from apis.restapi import Login
另外,你也可以使用两个 .insert
调用,这样可以把 /new
和 /new/uiautomation
加入到 sys.path
中,并简化导入为:
from apis.runner import Runner
from apis.restapi import Login
不过,这样会有点混淆,因为有两个目录都叫 apis
,这并不是最理想的情况。