
imp库,python进入import内部
发布日期:2021-05-07 18:06:09
浏览次数:25
分类:精选文章
本文共 1542 字,大约阅读时间需要 5 分钟。
Warning⚠️
更新于2020年 imp库在python3里面已经不推荐使用了imp模块提供了一个可以实现import语句的接口。
使用imp可以用来导入模块和类。imp.PY_SOURCE ----1
imp.PY_COMPILED------2 imp.C_EXTENSION------3imp.get_suffixes()
返回一个列表,列表的元素是三元素元组。 Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be ‘r’ for text files or ‘rb’ for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.imp.find_module(name, [,path])
返回值是三元素元组file, pathname, description file is an open file object positioned at the beginning, pathname is the pathname of the file found, and description is a 3-element tuple as contained in the list returned by get_suffixes() describing the kind of module found.这里的file可以理解为通过open()打开的一个句柄
例如:a = open(’/etc/test.sh’)的这个aimp.load_module(name, file, pathname, description)
例子就是uts中env.py
这个是env.py这个文件里面定义一个类class A(object) pass
下面是myB.py
import osimport sysimport imp# dir就是env.py所在的目录dir = os.path.dirname(os.path.abspath())# 这里有个注意点,可以选择从多个目录中找[dir1, dir2],若果没有找到env会报ImportErrorfile, path_name, description = imp.find_module('env', [dir])# 这一步就是导入env这个模块,让B成为A类的别名B = imp.load_module('env', file,path_name, description).A
当我在其他文件中需要使用B类的时候
from myB import B好处:我从myB导入了B,但B实际的定义是位于env.py中的A类,所以当我的env.py处于不同位置的时候,我可以导入不同的类B
官方例子,用完之后记得关闭文件
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月29日 15时16分35秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
“/”应用程序中的服务器错误。
2019-03-05
MUI之ajax获取后台接口数据
2019-03-05
使用sqlserver 查询不连续的数据
2019-03-05
用div+css+html+js 实现图片放大
2019-03-05
mui返回到父页页面并进行刷新
2019-03-05
小程序滑块视图容器的使用
2019-03-05
考研数据结构LeetCode入门题
2019-03-05
(原创)在Linux上安装运行Python3(CentOS7为例)
2019-03-05
快速学习汇编之 通用寄存器
2019-03-05
快速学习汇编之 常见汇编指令
2019-03-05
变量覆盖漏洞
2019-03-05
java 之 集合篇
2019-03-05
weblogic之cve-2015-4852
2019-03-05
Java注释
2019-03-05
水调歌头·1024
2019-03-05
对不起
2019-03-05
C++ 函数重载
2019-03-05
matlab文件管理
2019-03-05
Printer Queue UVA - 12100
2019-03-05
【并发编程】实现多线程的几种方式
2019-03-05