[英]Python: Create list of user-defined methods from a module and referencing/calling them by user input
对于标题的混乱,我深表歉意。
我正在解决一个问题,我想在main.py的子目录中有一个模块。 我希望子目录中有任意数量的.py文件。 在这里,我想输入用户输入,例如字符串“ foo”,然后搜索该模块中的所有方法,如果存在则调用它。 我正在查看dir或inspect模块的某种弗兰肯斯坦组合,以及getattr / hasattr方法,但是还没有运气找出一种可行的方法。
inspect.getmembers(module_name, inspect.ismethod)
这给我带来了很多不确定的预定义方法,我不确定如何进行排序。 如果有更好的解决方法,TYIA。 否则,我将如何处理上述情况?
对于您的具体情况,这应该可行。 循环浏览子目录中的所有文件,尝试将它们作为模块导入,并尝试查找并执行您所给定名称的函数。
import importlib, os
pkg = 'some_pkg' # this must be a python package
for x in os.listdir(pkg):
try:
module = importlib.import_module(pkg + '.' + x.replace('.py', ''))
fnc = getattr(module, 'foo')
fnc()
# break in case you want to stop at the first 'foo' fnc you find
except:
print('no foo here, or not a module!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.