Importlib de Python

python importlib

Hay códigos similares en el código fuente de OpenStack, así que pruebe la función de este módulo.

Estructura de código

[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

Efecto de ejecución del módulo de llamada

python call.py
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10

Importar llamada y ejecutarla dinámicamente

#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入
mod = importlib.import_module('call')

llevado a cabo

python test2.py 
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10

Importar llamada y asignarla a mod print mod

[root@ceph01 python]# cat test2.py 
#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入

mod = importlib.import_module('call')
print mod

llevado a cabo

[root@ceph01 python]# python test2.py 
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
<module 'call' from '/python/call.pyc'>

Importar llamada y asignar a mod para imprimir el tipo de datos de mod

cat test2.py 
#!/usr/bin/env python
#coding:utf8
import importlib #导入importlib模块,importlib模块用于动态导入

mod = importlib.import_module('call')

print mod
print type(mod)

llevado a cabo

python test2.py 
1,2,3,4
<type 'unicode'>
[[1, 2, 3, 4]]相加元素和为10
<module 'call' from '/python/call.pyc'>
<type 'module'>

Supongo que te gusta

Origin blog.csdn.net/weixin_40548182/article/details/111587492
Recomendado
Clasificación