【发布时间】:2019-10-05 15:14:26
【问题描述】:
什么?
我正在尝试将文件中的所有函数(给定路径)导入列表/字典
目前我正在使用here 和here 所说的内容。结果是这样的
import inspect
import importlib.util
def functions_from_file(path_to_module):
spec = importlib.util.spec_from_file_location("my_module",
path_to_module)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
custom_functions = inspect.getmembers(module, inspect.isfunction)
return dict(custom_functions)
至少在我看来,这似乎很令人费解。有更好/更清洁的方法吗?
为什么?
我这样做的原因是我希望用户能够指定一个包含将在我的代码中间执行的函数列表的文件。所以文件可能看起来像:
def fun1(my_dict):
my_dict['foo'] = my_dict['bar']*2
def fun2(my_dict):
my_dict['baz'] = my_dict['foo'] - my_dict['bar']
然后在我的代码中应该有类似
for fun in functions_list:
fun(my_dict)
【问题讨论】:
-
将目录添加到
sys.path然后正常导入呢?否则,看看使用插件库,像pluginBase 这样的东西听起来可以做你想要的。
标签: python python-3.x python-import