imp库,python进入import内部

Warning⚠️
更新于2020年 imp库在python3里面已经不推荐使用了

imp模块提供了一个可以实现import语句的接口。
使用imp可以用来导入模块和类。

imp.PY_SOURCE ----1
imp.PY_COMPILED------2
imp.C_EXTENSION------3

imp.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’)的这个a

imp.load_module(name, file, pathname, description)

例子就是uts中env.py
这个是env.py这个文件里面定义一个类

class A(object)
	pass

下面是myB.py

import os
import sys
import imp
# dir就是env.py所在的目录
dir = os.path.dirname(os.path.abspath())
# 这里有个注意点,可以选择从多个目录中找[dir1, dir2],若果没有找到env会报ImportError
file, 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

官方例子,用完之后记得关闭文件
这里写图片描述


posted @ 2022-03-06 10:40  叶常落  阅读(562)  评论(0编辑  收藏  举报