开发者

Calling methods from a dynamic list of modules

I'm trying to do two things here, dynamically import all modules in a directory (the amount/names are unknown) and then for each of those modules found call a function called checkMe(). checkM开发者_如何学Ce() is guaranteed to be in each module, so there is no need to check. This is what I have so far:

Import

import sys
import os
import glob

pathname = os.path.dirname(sys.argv[0]) + "/"
pathname = pathname + "/modules/"

__modules__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(pathname)+"/*.py")]

for module in __modules__:
    __import__(module)

Calling checkMe()

for module in __modules__:
    m = getattr(sys.modules[__name__], module)
    getattr(m, 'checkMe').__call__()

But I get this error:

AttributeError: 'module' object has no attribute 'sendme'

(sendme is the first module)

Any help is greatly appreciated... thank you!


__import__ has some tricky semantics regarding packages (directories containing an __init__.py) vs modules. You would need to use the fromlist argument to make it work. As it is, running a module by path is easiest with runpy (from the comments: run_path needs Python 2.7 or newer):

import runpy
runpy.run_path('path/to/file.py')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜