简体   繁体   中英

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]
    module = __import__('invenio.' + module_name)
    doctest.testmod(module)

A module can be dynamically loaded using __import__ eg

my_module = __import__("mymodule")

and then passed to testmod eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM