python执行子程序_Python关于import的实验(6) 在子包中的模块的import语句作为子程序被调用并且也可以作为主程序独立执行,则必须要使用绝对导入...

本文探讨Python中,如何在子程序中正确使用import语句,既能作为子程序被调用,也能作为主程序独立运行。重点在于理解绝对导入的重要性,并通过示例解释了在模块布局中,当主程序和子程序位于不同层级时,如何处理import语句,以避免`ModuleNotFoundError`。同时,展示了在主程序和子程序中添加`sys.path.append(os.getcwd())`的必要性。
摘要由CSDN通过智能技术生成

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值