python import子模块

wfifi 发布于 2017/01/12 16:44
阅读 203
收藏 0

在windows 10, python3.5.2环境,一个项目结构如下:

pypkg
|   __init__.py
|
\---subpkg
    |   suba.py
    |   subb.py
    |---__init__.py

两个__init__.py内容为空

suba.py内容:

def funA():
	print("Suba funA")
	
def funB():
	print("Suba funB")



subb.py

import suba

def funC():
	print("Suba funA")
	
def funD():
	print("Suba funB")
	
def funE():
	print("Subb funE call ")
	suba.funA()



在subpkg目录下运行python交互界面,下面这样没问题

>>> import subb
>>> subb.funE()
Subb FunE call
Suba funA



转到 pypkg 目录下运行python交互界面

>>> from subpkg import subb
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Z:\xyz\pypkg\subpkg\subb.py", line 2, in <module>
    import suba
ImportError: No module named 'suba'



这个要怎么修改才能在pypkg下运行正常,同样在subpkg下交互也正常?


加载中
1
S
Se7enLiu
subb.py中的import suba修改为from . import suba
wfifi
wfifi
这样在pypkg下from subpkg import subb是对了,但在subpkg下import subb出现了SystemError: Parent module '' not loaded, cannot perform relative import
0
mickelfeng
mickelfeng
我的是2.7 怎么没问题呢
S
Se7enLiu
2.7的确没问题,在3就不行了
返回顶部
顶部