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.
# 如果一定要作为主程序来执行import语句,
# 而且同时要能被其他程序如test4main.py来调用
# 那么必须使用绝对导入,并且添加sys.path.append(os.getcwd())
# 不能使用相对导入,因为相对导入是基于当前模块的__name__,
# 而主程序的__name__总是'__main__',
# 所以不能使用相对导入,只能使用绝对导入.
# 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.
文件夹的布局:
test4main_1.py
# from sound.filters import test4cxq
from sound.filters import test4cxq_1
sound\filters\test4cxq_1.py
# 绝对导入
import sound.effects.surround # 这行代码被test4main.py正常调用
print(sound.effects.surround.info)
r'''
这部分代码不能直接作为主程序调用,
否则会报错,如下:
Traceback (most recent call last):
File "c:\Users\chenxuqi\Desktop\新建文件夹\testImport\sound\filters\test4cxq_1.py",
line 4, in
import sound.effects.surround # 这行代码被test4main.py正常调用
ModuleNotFoundError: No module named 'sound'