开发者

Python modules matching a pattern

开发者 https://www.devze.com 2022-12-22 02:10 出处:网络
I\'d like to run doctests 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.

I'd like to run doctests 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.

0

精彩评论

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

关注公众号