sunshinekitty sunshinekitty - 1 month ago 6
Python Question

Inconsistent results with pkgutil.iter_modules

I'm trying to print out all submodules of a given module in a package. However when running the function to do this I get mixed results, can anyone explain why this is happening and how to avoid it?

Project layout:

/Users/me/projects/project
setup.py
/project
__init__.py
tool.py
/projectdir
__init__.py
test.py


/Users/me/projects/project/project/tool.py:

import pkgutil


for importer, modname, ispkg in \
pkgutil.iter_modules('project.projectdir',
prefix='project.projectdir.'):
if not ispkg:
print '{}'.format(modname)


/Users/me/projects/project/project/projectdir/test.py

def one():
return 'one'


This should ideally print out all modules inside
/projectdir
however I get mixed results.

This is right:

$ cd /Users/me
$ project
>> project.projectdir.test


These are wrong:

$ cd /Users/me/projects
$ project
>>

$ cd /Users/me/projects/project
$ project
>> project.projectdir.one

Answer

Using .__path__ avoids any chance of a relative path for iteration. In your example instead of passing project.projectdir. you will be passing /Users/me/projects/project.

import pkgutil

# import module that will be inspected
import project


package = project
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix='project.projectdir.'):
    if not ispkg:
        print '{}'.format(modname)