如何从Python目录中的每个模块调用函数? [英] How to call a function from every module in a directory in Python?

查看:94
本文介绍了如何从Python目录中的每个模块调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是将目录/包中的每个模块导入,然后在每个子模块上调用相同的函数,而无需知道它们的名称或名称.

What I want to do is import every module in a directory/package and then call the same function on each submodule, without knowing their names or how many there are.

如果您熟悉MCEdit(Minecraft的第三方工具),其过滤器系统就是这样.所有作为筛选器的.py文件都放在一个目录中,然后MCEdit导入每个筛选器,并能够显示导入的筛选器列表,并执行每个筛选器的perform(level,box,options)函数.

If you're familiar with MCEdit, (a 3rd party tool for Minecraft) its filter system is like this. All the .py files which are filters go in a directory, and then MCEdit imports each one and is able to show a list of imported filters and execute each one's perform(level, box, options) function.

推荐答案

查找该目录中的每个模块,使用__import__导入它,然后调用该函数.例如:

Find every module in that directory, use __import__ to import it, then call the function. For example:

for file_name in os.listdir('path/to/modules'):
    if file_name.startswith('.') or not file_name.ends_with('.py'):
        continue
    module_name = file_name[:-3]
    module = __import__(module_name)
    module.some_function()

但是,这并不能解决所有情况,特别是某些模块可能是用C编写的,并且具有.pyd扩展名而不是.py.您要考虑这个吗? sys.path中可能有几个条目.您要支持所有这些,还是只搜索一个目录?模块可以驻留在ZIP文件中.您将必须支持这一点.借助导入挂钩,可能会即时生成模块,并且可能没有办法对其进行枚举.搜索模块时,您必须决定要走多远.但是,找到它们之后,就可以轻松导入和使用它们.

However, this does not account for all cases—in particular, some modules might be written in C and have the .pyd extension rather than .py. Do you want to account for that? There are probably several entries in sys.path. Do you want to support all of them, or only search one directory? Modules can reside inside of a ZIP file. You would have to support that. And with import hooks, modules could probably be generated on the fly, and there might be no way to enumerate them. You have to decide how far you want to go when searching for modules. But after you’ve found them, it’s easy to import and use them.

这篇关于如何从Python目录中的每个模块调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆