首页 > 解决方案 > Python - 从当前文件中获取自定义模块

问题描述

我正在尝试在当前文件中获取导入的自定义模块(我自己创建的模块)的列表,但我找不到实现它的正确方法。

例如:

<test.py>
import sys
import foo
import bar

我想获得一个[foo, bar]排除sys模块的列表。

标签: python

解决方案


可以说,如果文件位于当前文件附近或某个子文件夹中,那么它是“我们的”模块,而不是系统一。

对于这个示例,我创建了三个文件:main.py、other.py 和 another.py,并将 whem 放在一个文件夹中。

main.py 的代码是:

# 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())

而这段代码实际上输出 ["other", "another"]

这种方法有一个问题:如果你导入模块,它以某种方式位于上层文件夹中,它不会被检测到。


推荐阅读