御医 发表于 2023-4-6 18:01:43

python中动态导入文件的方法

1.简介

在实际项目中,我们可能需要在执行代码的过程中动态导入包并执行包中的相应内容,通常情况下,我们可能会将所需导入的包及对象以字符串的形式传入,例如test.test.run,下面将介绍如何动态导入。
假设存在如下包:
https://img-blog.csdnimg.cn/2c0daac1147346c4ba7724edd359c8c2.png
其中test.py的内容如下:
count = 1


def run():
    print("run")下面,我们将使用test.test2.run来动态导入run方法
一、使用内置的__import__方法导入相应的包

module = __import__(
    "test2.test", globals=globals(), locals=locals(), fromlist=["run"]
)
print(module)
print(getattr(module, "run"))
print(getattr(module, "count"))


# 结果
<module 'test2.test' from 'c:\\Users\\ts\\Desktop\\日报\\2023.1.5\\test2\\test.py'>
<function run at 0x000002EC1CB9B250>
1__import__(name,globals=None,locals=None,fromlist=(),level=0)-> module含义:导入模块。因为此函数是供Python解释器使用的,而不是一般用途,所以最好使用importlib.import_module()以编程方式导入模块。

[*]name:需要导入的模块的名称,包含全路径。
[*]globals: 当前范围的全局变量,正常设置为globals()。
[*]locals:当前范围的局部变量,正常不需要使用,设置为locals()。
[*]fromlist: 控制导入的包,例_import__('a.B',…)在fromlist为空时返回包a,但在fromlist不为空时,返回其子模块B,理论上只要fromlist不为空,则导入的是整个的name的包。
[*]level:判断路径是绝对的还是相对的,0是绝对的,正数是相当于当前模块要搜索的父目录的数量。
二、使用importlib.import_module进行导入

from importlib import import_module

module = import_module(name="test2.test")
print(module)
print(getattr(module, "run"))
print(getattr(module, "count"))

import_module(name, package=None)

[*]name: 需要导入的包名。
[*]package: 需要相对导入的包名称,目前发现设置package后,name只能设置package以内的内容,示例如下:
存在如下包
https://img-blog.csdnimg.cn/2ee6601561de4c35b746c85432b52397.png
module = import_module(name="..test2", package="test3.test3")
print(module)
print(getattr(module, "run"))
print(getattr(module, "count"))
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
# 结果
<module 'test3.test2' from 'c:\\Users\\ts\\Desktop\\日报\\2023.1.5\\test3\\test2.py'>
<function run at 0x0000024665C00310>
1上述结果导入了test3.test2,name只能设置package以内的包。
三、直接使用exec拼接代码执行(不推荐)

str_data = "test2.test"


exec(
    "import {} as t\n\
\
print(t.run())\n\
print(t.count)\n".format(
      str_data
    )
)上述方式不推荐,其实就是相当于本地导入然后将代码作为参数添加到exec的参数中。
补充
关于importlib模块,还有一个方法我们需要去注意一下,就是reload方法,但我们在代码执行过程中动态的修改了某个包的内容时,想要立即生效,可以使用reload方法去重载对应的包即可。

来源:https://www.cnblogs.com/djdjdj123/p/17293329.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: python中动态导入文件的方法