0

I want to import all modules from a particular directory of a package which I installed using pip, that is, it lies in site-packages.

What I tried

Let's say the package name is package and it has a directory called directory. It has many files like a.py, b.py, etc. I need to import all of them. I listed all files in directory using in-built __file__, which isn't the problem. When I tried to import the modules using importlib.import_module, I got ModuleNotFoundError even though I'm 100% percent sure they exist. I used relative import.

Code Snippet

modules is the list of all files in directory

for module in modules:
    importlib.import_module('.'+module, 'C:\\Users\\.....\\package\\directory')

ModuleNotFoundError: No module named 'C:\\Users\\.....\\package\\directory'

Finally

What am I doing wrong and what is the right approach to refer site-packages?

Shivang Kakkar
  • 421
  • 3
  • 15

1 Answers1

0

create an empty __init__.py file under the directory that you want to execute

import pkgutil
import sys


def load_all_modules_from_dir(dirname):
    for importer, package_name, _ in pkgutil.iter_modules([dirname]):
        full_package_name = '%s.%s' % (dirname, package_name)
        if full_package_name not in sys.modules:
            module = importer.find_module(package_name
                        ).load_module(full_package_name)
            print module


load_all_modules_from_dir('site-packages')
Shivang Kakkar
  • 421
  • 3
  • 15
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
  • This code will only work if run in parent directory of `site-packages` which defeats the whole purpose. Also, I would need path to directory not site-packages But even if I get the absolute path to `site-packages` or `directory` it gives import error – Shivang Kakkar Dec 30 '21 at 13:31