python importlib
OpenStack源代码中有类似代码,所以测试下这个模块的作用。
代码结构
[root@ceph01 python]# ll
总用量 24
drwxr-xr-x. 2 root root 6 11月 17 10:13 bak
-rw-r--r--. 1 root root 373 12月 23 12:30 call.py
-rw-r--r--. 1 root root 323 12月 23 12:34 call.pyc
drwxr-xr-x. 3 root root 76 11月 17 17:29 conf
drwxr-xr-x. 3 root root 110 12月 23 12:32 modu
drwxr-xr-x. 3 root root 4096 12月 2 15:51 ssh
-rw-r--r--. 1 root root 219 12月 23 12:38 test2.py
-rw-r--r--. 1 root root 3004 12月 23 12:35 test.py
call模块执行效果
python call.py
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
导入call并动态执行
#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入
mod = importlib.import_module('call')
执行
python test2.py
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
导入call并赋值给mod打印mod
[root@ceph01 python]# cat test2.py
#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入
mod = importlib.import_module('call')
print mod
执行
[root@ceph01 python]# python test2.py
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
<module 'call' from '/python/call.pyc'>
导入call并赋值给mod打印mod数据类型
cat test2.py
#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入
mod = importlib.import_module('call')
print mod
print type(mod)
执行
python test2.py
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
<module 'call' from '/python/call.pyc'>
<type 'module'>