1 同一文件夹下的模块导入
[root@hding cases]# tree
.
|-- __init__.py
|-- test_arp.py
|-- upgrade.py
`
upgrade.py
1 #!/usr/bin/env python
2 #coding:utf-8
3
4
5 def upgrade():
6 print 'upgrade is a important thing'
test_arp.py
1 #!/usr/bin/env python
2 #coding:utf-8
3 import upgrade
4
5 def test_arp():
6 print 'arp is a layer two protocol'
7
8 if __name__ == '__main__':
9 test_arp()
10 upgrade.upgrade()
-------------------------------------------------------------
[root@hding cases]# !py
python test_arp.py
arp is a layer two protocol
upgrade is a important thing
在同一级目录时,文件可以直接import,最好不要用from upgrade import upgrade,直接导函数,而应该导模块,因为函数有可能重名,到main函数中应用时不知道这个函数来自何方,如该例中如果直接导函数,则main函数中不是upgrade.upgrade(),而是直接upgrade()调用函数,并不知道该函数来自何方
2 不同文件夹下的包导入
[root@hding gui_automation]# tree
.
|-- __init__.py
|-- cases
| |-- __init__.py
| |-- __init__.pyc
| |-- test_arp.py
| |-- upgrade.py
| `-- upgrade.pyc
|-- general
| `-- test_run.py
`-- test_main.py
gui_automation文件夹下存放两个目录,cases/ 和 general/,test_main.py调用upgrade模块
test_main.py
1 #!/usr/bin/env python
2 #coding:utf-8
3
4 from cases import upgrade
5
6 upgrade.upgrade()
---------------------------------
[root@hding gui_automation]# !py
python test_main.py
upgrade is a important thing
test_main在上层,如果是test_run.py 调用upgrade,则需要跨目录
test_run.py
1 #!/usr/bin/env python
2 #coding:utf-8
3 import sys
4 sys.path.append("/data/python/core_python/Chapter12/gui_automation/")
5
6 from cases import upgrade
7
8
9 if __name__ == '__main__':
10 upgrade.upgrade()
---------------------------------------------------------------------------
[root@hding gui_automation]# python general/test_run.py
upgrade is a important thing
test_run需要找cases目录下的模块,首先要能找到该目录,因此需要给系统添加路径,使得python能找到该目录再import
如果在cases/case/下再建一个case.py,导入时就加入了层级关系,在python中用.来表示层级关系
[root@hding gui_automation]# tree
.
|-- __init__.py
|-- __init__.pyc
|-- cases
| |-- __init__.py
| |-- __init__.pyc
| |-- case
| | `-- case.py
| |-- test_arp.py
| |-- upgrade.py
| `-- upgrade.pyc
|-- general
| `-- test_run.py
`-- test_main.py
general/test_run.py
1 #!/usr/bin/env python
2 #coding:utf-8
3 import sys
4 sys.path.append("/data/python/core_python/Chapter12/gui_automation")
5
6 from cases import upgrade
7 from cases.case import test_case
8
9
10 if __name__ == '__main__':
11 upgrade.upgrade()
12 test_case.test_case()
总结:
模块只是一个py文件
包指的是一个文件夹下的多个模块,其中必需含有__init__.py
同一目录下直接import
不同目录下用from A import *, 其中A的上一级目录必需在python的环境变量中,否则找不到
不同目录下的层级关系用。 from A.B import *
sys.path.append('c:\\work\\python\\XX')