[python] 动态import

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zongza/article/details/88386148

如何在调用地时候才import所需要的文件?

使用__import__方法

decodeData.py文件中由所需要的类的定义:

class decodeData():
    @staticmethod
    def d():
        print('decodeData')

想在另一个文件test.py中生成这个类,且是在需要的时候才import

# 首先将decodeData.py所在路径加入到系统路径中
import os,sys
base_dir = 'D:/pycharm_proj/0307_django/test'
sys.path.append(base_dir)

name = 'decodeData'

def test(name):
    # 使用__import__方法动态导入
    p = __import__(name,globals(),locals(),level=0)

    print(dir(p))
    globals()[name] = p.__dict__[name]

    instance = eval(name)

    instance.d()

test(name)

结果:

['NamedTemporaryFile', 'TemporaryFile', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'audio', 'audio_file', 'b64encode', 'decodeData', 'fp', 'np', 'os', 'soundfile', 'stream']
decodeData

参考:

多重 import : https://blog.csdn.net/longzhiwen888/article/details/46604265

python import : http://www.runoob.com/python/python-modules.html

循环import:https://www.zhihu.com/question/19887316

猜你喜欢

转载自blog.csdn.net/zongza/article/details/88386148
今日推荐