Python动态导入模块的方法实例分析
作者:Bigberg 时间:2022-06-08 17:56:45
本文实例讲述了Python动态导入模块的方法。分享给大家供大家参考,具体如下:
一、正常导入模块
正常模块导入方式: import module(模块路径)
同时导入多个模块:
import os,sys,socket
二、动态导入模块
动态导入模块允许我们通过字符串形式来导入模块
2.1 __import__函数,接受一个字符串参数
import os, sys
my_sys = __import__('sys')
my_os = __import__('os')
print(sys.version)
print(my_sys.version)
print('-------------')
print(os.getcwd())
print(my_os.getcwd())
输出:
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]
-------------
G:\python\untitled\study8
G:\python\untitled\study8
我们将sys, os 模块名当中参数传入__import__
函数中,可以看出my_sys 和my_os 其实就是相当于 os , sys 模块了。
2.2 __import__函数导入自己的模块
我们在lib包中有一个test.py模块,我们如何通过__import__
函数来导入该模块呢?
# test.py内容
class Person(object):
def __init__(self):
self.name = 'bigberg'
# 导入模块
mod = __import__('lib.test') # 相当于获取了 lib 的路径
print(mod)
obj = mod.test.Person()
print(obj.name)
输出:
<module 'lib' from 'G:\\python\\untitled\\study8\\lib\\__init__.py'>
bigberg
2.3 动态导入模块列表
moduleNames = ['sys', 'os', 'socket']
print(type(map))
# 在python3 map函数不在是内置函数,而是class,返回的结果是 可迭代对象
print(isinstance(map(__import__, moduleNames), Iterator))
modules = list(map(__import__, moduleNames))
print(modules[0].version)
输出:
<class 'type'>
True
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]
现在的modules[0] 就相当于 sys 模块了。
2.4 importlib 模块
动态导入模块时,python官方建议使用importlib
模块,我们同样导入lib/test.py
import importlib
mod = importlib.import_module('lib.test') # mod相当于 test.py本身了,于上例不同
print(mod)
obj = mod.Person()
print(obj.name)
输出:
<module 'lib.test' from 'G:\\python\\untitled\\study8\\lib\\test.py'>
bigberg
希望本文所述对大家Python程序设计有所帮助。
来源:http://www.cnblogs.com/bigberg/p/7746828.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
CSS实现DIV完美垂直居中(支持多浏览器)
win7 x64系统中安装Scrapy的方法
![](https://img.aspxhome.com/file/2023/3/95553_0s.jpg)
python 自定义异常和异常捕捉的方法
asp获取完整url地址代码
Python下载ts文件视频且合并的操作方法
![](https://img.aspxhome.com/file/2023/5/76985_0s.jpg)
Python如何定义有默认参数的函数
如何对Python编译PyInstaller打包生成的exe文件进行反编译生成pyc、py源代码文件
![](https://img.aspxhome.com/file/2023/6/64286_0s.png)
简单了解python装饰器原理及使用方法
详解python使用递归、尾递归、循环三种方式实现斐波那契数列
![](https://img.aspxhome.com/file/2023/5/86155_0s.png)
python 合并多个excel中同名的sheet
![](https://img.aspxhome.com/file/2023/3/102943_0s.png)
详解Django关于StreamingHttpResponse与FileResponse文件下载的最优方法
关联的 script 标签
XML简易教程之三
关于CSS中字号控制的兼容性研究
Python学习笔记之函数的参数和返回值的使用
![](https://img.aspxhome.com/file/2023/4/114724_0s.png)
淘宝CSS框架研究(1):Reset CSS(八卦篇)
使用Python来编写HTTP服务器的超级指南
![](https://img.aspxhome.com/file/2023/2/90652_0s.png)