Python modules matching a pattern
I'd like to run doctest
s for a set of modules (glob: invenio.webtag*
) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod()
on all of them. Any ideas?
Edit: The solution:
import doctest
import glob
import os
import pkgutil
pkgpath = pkgutil.extend_path([], 'invenio')[0]
for module_path in glob.glob(pkgpath + '/webtag*.py'):
module_name = os.path.splitext(os.path.basename(module_path))[0]
开发者_Python百科module = __import__('invenio.' + module_name)
doctest.testmod(module)
A module can be dynamically loaded using __import__
e.g.
my_module = __import__("mymodule")
and then passed to testmod
e.g.
doctest.testmod(my_module)
Assuming you can build a list of the matching modules using either glob.glob or filtering the results from os.listdir you should be able to use this approach.
Update:
To import invenio.webtag
try using a fromlist:
module = __import__('invenio.webtag', globals(), locals(), ['invenio'], -1)
see this documentation for the explanation.
精彩评论