python相对导包问题(迁移)

导包分为:绝对路径、相对路径

在测试时发现不能够使用相对路径

查过之后才知道:

运行模块(如:main.py)中导包只能使用绝对路径,不能使用相对路径

官方文档:

Note that relative imports are based on the name of the current module. Since the name of the main module is always __main__, modules intended for use as the main module of a Python application must always use absolute imports.

 

例子:

image

main.py

from pack.test import run
run()

test.py

from .sub_pack.sub_test import a
def run():
print(a)

sub_test

a = 1

项目中main.py才是主程序,所以只能有绝对路径;

而其他py文件中可以有绝对路径和相对路径

相对路径导入:

from .  import method/attr/class,只能从__init__中导入函数/变量等

from .m1 import class1与 from m1 import class1等同,都是从同级导入

 


update:

注意:绝对路径是从sys.path开始找,而相对路径是从当前路径开始找

 

 

 

参考:

ModuleNotFoundError: No module named '__main__.xxxx'

posted @ 2019-08-19 18:31  Justaman  阅读(511)  评论(0编辑  收藏  举报