gses
gses

Reputation: 21

Python - Get custom modules from current file

I am trying to get a list of the imported custom modules (modules I created by myself) in my current file but I could not find a proper way to achieve it.

For example:

<test.py>
import sys
import foo
import bar

I would like to get a list of [foo, bar] excluding the sys module.

Upvotes: 1

Views: 545

Answers (1)

MihanEntalpo
MihanEntalpo

Reputation: 2072

Lets say, that if file located near curent file, or in some subfolder, when it's "our" module, not system one.

For this example, I've created three files: main.py, other.py and another.py, and placed whem into one folder.

The code of main.py is:

# os and sys are needed to work
import sys
import os

import shutil
import io
import datetime
import other
import another

def get_my_modules():
    # Get list of modules loaded
    modules = list(sys.modules.keys())

    mymodules = []

    # Get current dir
    curdir = os.path.realpath(os.path.dirname(__file__))

    for m in modules:
        try:
            # if some module's file path located in current folder or in some subfolder
            # lets sey, that it's our self-made module
            path = sys.modules[m].__file__
            if path.startswith(curdir):
                mymodules.append(m)
        except Exception:
        # Exception could happen if module doesn't have any __file__ property
            pass

    # Return list of our moudles
    return mymodules

print(get_my_modules())

And this code actually outputs ["other", "another"]

This approach has a problem: If you import module, that somehow located in upper folder, it woudln't be detected.

Upvotes: 2

Related Questions