gpt4 book ai didi

Python3 使用 exec 动态导入 - 为什么 'as' 不被执行?

转载 作者:行者123 更新时间:2023-11-30 22:11:16 36 4
gpt4 key购买 nike

我有这个手动携带模块的代码

exec("import" + moduleName + " as selectedModule")
importlib.reload(selectedModule)

但是这段代码使得

name 'seletedModule' is not defined

在 python2.x 上没有发生这种情况。如何在 python3 上导入它?

最佳答案

如果您需要动态导入库,请不要使用exec它不安全

改用importlib.import_module

selected_module = importlib.import_module(module_name)
importlib.reload(selected_module)
<小时/>

至于您收到的错误:您可能在函数作用域内调用 exec ,因此您需要手动设置 globals localsexec ( Using a function defined in an exec'ed string in Python 3 ) 中的相同。解决方法:

exec("<do-stuff>", globals())

关于Python3 使用 exec 动态导入 - 为什么 'as' 不被执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472607/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com