• 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

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


  • 相关阅读:
    环境变量学习(二)Mac 可设置环境变量的位置
    环境变量学习(一)简介、查看
    shell学习(二)安装shell环境
    npm学习(十八)npm scripts 使用指南
    nodemon学习(二)实战
    nodemon学习(一)简介、安装、配置、使用
    Error: listen EADDRINUSE 127.0.0.1:8888错误解决
    树莓派创建wifi热点
    JavaScript中的数据类型转换
    Packstack 搭建 OpenStack 报 MariaDB 错误的处理
  • 原文地址:https://www.cnblogs.com/lineuman/p/15970953.html
Copyright © 2020-2023  润新知