def get_all_modules(
module_name: str, path: typing.Optional[typing.Sequence[str]]=None,
) -> typing.AbstractSet[str]:
"""Find all module names from given ``module_name``.
:param str module_name: The name of root module which want to find.
:param list[str] or None path: The path to find the root module.
:return: The set of module names.
.. code-block:: python
>>> get_all_modules('ormeasy')
{'ormeasy.alembic', 'ormeasy.common', 'ormeasy.sqlalchemy'}
>>> get_all_modules('ormeasy.common')
{'ormeasy.common'}
"""
root_mod, *_ = module_name.split('.')
module_spec = importlib.machinery.PathFinder.find_spec(root_mod, path)
if not module_spec:
if path:
raise ValueError(
'{!s} inexists or is not a python module in {!s}'.format(
root_mod, path
)
)
raise ValueError(
'{!s} inexists or is not a python module'.format(root_mod)
)
module_name_with_dot = root_mod + '.'
if module_spec.submodule_search_locations:
module_names = {
name
for _, name, _ in pkgutil.walk_packages(
module_spec.submodule_search_locations,
prefix=module_name_with_dot
)
}
else:
module_names = {
name
for _, name, _ in pkgutil.walk_packages(
[os.path.dirname(module_spec.origin)]
)
if name.startswith(module_name_with_dot) or name == module_name
}
return {m for m in module_names if m.startswith(module_name)}
评论列表
文章目录