在Python中动态加载模块中的所有名称
如何从some.module import*中执行在Python中动态加载模块中的所有名称,python,python-3.x,Python,Python 3.x,如何从some.module import*中执行,其中在字符串变量中定义了模块的名称?此代码从操作系统导入所有符号: import importlib # Load the module as `module' module = importlib.import_module("os") # Now extract the attributes into the locals() namespace, as `from .. # import *' would do if hasattr(m
,其中在字符串变量中定义了模块的名称?此代码从操作系统导入所有符号:
import importlib
# Load the module as `module'
module = importlib.import_module("os")
# Now extract the attributes into the locals() namespace, as `from ..
# import *' would do
if hasattr(module, "__all__"):
# A module can define __all__ to explicitly define which names
# are imported by the `.. import *' statement
attrs = { key: getattr(module, key) for key in module.__all__ }
else:
# Otherwise, the statement imports all names that do not start with
# an underscore
attrs = { key: value for key, value in module.__dict__.items() if
key[0] != "_" }
# Copy the attibutes into the locals() namespace
locals().update(attrs)
参见,例如,有关来自的后面的逻辑的更多信息。。。导入*
操作
现在,虽然这样做有效,但不应使用此代码。从命名模块中导入所有符号已经被认为是一种不好的做法,但使用用户给定的名称显然更糟糕。如果需要错误提示,请搜索PHP的register\u globals
。在Python中,内置的import函数实现了与使用import语句相同的目标,但它是一个实际的函数,并且以字符串作为参数
sys = __import__('sys')
变量sys现在是sys模块,就像您说的import sys一样
你所做的很可能是错的。。。在运行时在模块级别定义变量。这种方法迟早会给你带来麻烦。相反,将这些对象存储到数据结构中,例如dict,然后处理它。我这样做是为了根据环境变量加载开发、生产和测试设置,这很好,不过在这种情况下,您更可能希望模拟导入一些.module
,而不是从一些.module导入*
。确切地说,只需有条件地导入设置模块,而无需通过编程修改全局范围。类似于if production:from blablabla import productionsettings as settings,elif:…
这不是用户指定的名称,我需要根据环境变量it中的值加载开发、测试或产品设置文件<代码>“os”
是一个可以是任何内容的字符串。