Python-从当前文件中获取自定义模块
我试图在当前文件中获取导入的自定义模块(我自己创建的模块)的列表,但我找不到合适的方法来实现它 例如:Python-从当前文件中获取自定义模块,python,Python,我试图在当前文件中获取导入的自定义模块(我自己创建的模块)的列表,但我找不到合适的方法来实现它 例如: <test.py> import sys import foo import bar 导入系统 进口食品 进口栏 我想得到一个[foo,bar]列表,不包括sys模块。假设文件位于当前文件附近或某个子文件夹中,当它是“我们的”模块而不是系统模块时 对于本例,我创建了三个文件:main.py、other.py和other.py,并将whem放在一个文件夹中 main.py的代码
<test.py>
import sys
import foo
import bar
导入系统
进口食品
进口栏
我想得到一个
[foo,bar]
列表,不包括sys
模块。假设文件位于当前文件附近或某个子文件夹中,当它是“我们的”模块而不是系统模块时
对于本例,我创建了三个文件:main.py、other.py和other.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())
这个代码实际上输出[“其他”,“另一个”]
这种方法有一个问题:如果您导入模块(不知何故位于上面的文件夹中),它将不会被检测到。非常感谢您的回复!但是,我的模块不在同一个文件中。例如,我所做的是:在同一个文件(test.py)中,我找到了当前模块modules=inspect.getmembers(sys.modules[name],inspect.ismodule),但我现在知道如何区分。如果您知道模块位于何处,您可以增强此功能,检查“指定文件夹中的模块文件是否存在”,并确定它是“您的”另外,如果你没有太多自己的模块,你可以在每个人的开头加上“\uuuuMyModule\uuuuu=True”这样的行。因此,函数可以检查,如果模块具有属性“\uuuuMyModule\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu