这个问题出现在同一个包内两个文件互相导入时加上了**.**package
例如
#package->test.py
from .layer import ll
ll()
class class2():
def __init__(self) -> None:
print('hello this is class2')
#package->ll.py
class ll():
def __init__(self) -> None:
print('hello this ll')
这样就会报错
但是当你把.去掉就正常运行
#package->test.py
from layer import ll
ll()
class class2():
def __init__(self) -> None:
print('hello this is class2')
#package->ll.py
class ll():
def __init__(self) -> None:
print('hello this ll')
对此,我觉得是相对路径引入的问题
但是,当你保持这个格式想在package2里引入test的时候,发现又会报错
```python
#package->test.py
from layer import ll
ll()
class class2():
def __init__(self) -> None:
print('hello this is class2')
#package2->test2.py
import package2.test1.class2 as class2
class2()
发现又会报错,错误内容如下
ydevd_runpy.py", line 124, in _run_code
exec(code, run_globals)
File "/disk3/wzh/wzh_test/test2.py", line 7, in <module>
import module.test1.class2 as class2
File "/disk3/wzh/wzh_test/module/test1.py", line 1, in <module>
from layer import ll
ModuleNotFoundError: No module named 'layer'
这就很头疼了,我尝试修改了几种方法,目前奏效的时添加系统路径
系统路径可以理解成python运行时需要依赖包时寻找的路径,如
import sys
print(sys.path)
output:
['/disk3/wzh/nlp-tutorial/1.transformer_raw_code', '/disk3/wzh/miniconda3/envs/dl/lib/python38.zip', '/disk3/wzh/miniconda3/envs/dl/lib/python3.8', '/disk3/wzh/miniconda3/envs/dl/lib/python3.8/lib-dynload', '', '/disk3/wzh/.local/lib/python3.8/site-packages', '/disk3/wzh/miniconda3/envs/dl/lib/python3.8/site-packages', '/disk3/wzh/miniconda3/envs/dl/lib/python3.8/site-packages/setuptools/_vendor', '/disk3/wzh/PyTorch-Tutorial-2nd/code/chapter-9/d_bert/', '/disk3/wzh/PyTorch-Tutorial-2nd/code/chapter-9/d_bert/']
为了规避掉上面两个报错,只需要保持绝对依赖的同时,为子模块添加系统路径即可
#package->test.py
from layer import ll
ll()
class class2():
def __init__(self) -> None:
print('hello this is class2')
#package->ll.py
class ll():
def __init__(self) -> None:
print('hello this ll')
#package2->test2.py
import sys
sys.path.append('/disk3/wzh/package')
import package2.test1.class2 as class2
class2()