包可用于将一组模块分组到一个自定义的包名称下。
[root@VM_131_54_centos tt]# tree
.
|– main.py
|– recv
| -- recvmsg.py
– send
|– init.py
|– init.pyc
|– sendmsg.py
send是个目录,且里面有个init.py就可以成为一个包。而recv目录下没有。
在这两个目录的上层测试是否能够被导入,可以看出,没有init.py的就导入失败。
[root@VM_131_54_centos tt]# ls
main.py recv send
[root@VM_131_54_centos tt]# ipython
In [1]: from recv.recvmsg import *
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-ed208f11484c> in <module>()
----> 1 from recv.recvmsg import *
ImportError: No module named recv.recvmsg
In [2]: from send.sendmsg import * #导入成功
init.py文件可以为空,里面什么都不写,只有一个空文件。只要是导入模块时,该模块是第一次导入,就会执行init.py中的代码。如:sendmsg被导入过一次,那么有sendmsg.pyc文件,此时再次导入就不会执行init.py。
在init.py模块为空的情况下,只import 包名 ,如:import send 。那么不会导入包中所包含的所有模块。如下所示:
[root@VM_131_54_centos tt]# ipython
In [1]: import send
In [2]: send.sendmsg.sendMsg()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-731caa8df27a> in <module>()
----> 1 send.sendmsg.sendMsg()
AttributeError: 'module' object has no attribute 'sendmsg'
但是如果在init.py中添加如下语句就可行:
[root@VM_131_54_centos send]# cat __init__.py
import sendmsg #添加一句
[root@VM_131_54_centos send]# ls
__init__.py __init__.pyc sendmsg.py sendmsg.pyc
[root@VM_131_54_centos tt]# ls
main.py recv send
[root@VM_131_54_centos tt]# ipython
In [1]: import send
In [2]: send.sendmsg.sendMsg()
已经发送信息
这样只导入包的话,会执行init.py中的语句,这样就自动导入了sendmsg模块。