gpt4 book ai didi

python - 将 python 模块导入字典(用作 execfile() 中的全局变量)?

转载 作者:太空狗 更新时间:2023-10-29 22:08:21 25 4
gpt4 key购买 nike

我使用 Python execfile() 函数作为处理配置文件的一种简单但灵活的方式——基本上,我的想法是:

# Evaluate the 'filename' file into the dictionary 'foo'.
foo = {}
execfile(filename, foo)

# Process all 'Bar' items in the dictionary.
for item in foo:
if isinstance(item, Bar):
# process item

这要求我的配置文件可以访问 Bar 类的定义。在这个简单的例子中,这是微不足道的;我们可以只定义 foo = {'Bar' : Bar} 而不是一个空的字典。但是,在实际示例中,我有一个要加载的完整模块。一个明显的语法是:

foo = {}
eval('from BarModule import *', foo)
execfile(filename, foo)

但是,我已经在我的顶层文件中导入了 BarModule,所以看起来我应该能够直接将 foo 定义为一组东西由 BarModule 定义,无需经过 evalimport 链。

有没有一种简单的惯用方法可以做到这一点?

最佳答案

也许你可以使用模块定义的__dict__

>>> import os
>>> str = 'getcwd()'
>>> eval(str,os.__dict__)

关于python - 将 python 模块导入字典(用作 execfile() 中的全局变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649824/

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