python - Python - 从当前文件中获取自定义模块
问题描述
我正在尝试在当前文件中获取导入的自定义模块(我自己创建的模块)的列表,但我找不到实现它的正确方法。
例如:
<test.py>
import sys
import foo
import bar
我想获得一个[foo, bar]
排除sys
模块的列表。
解决方案
可以说,如果文件位于当前文件附近或某个子文件夹中,那么它是“我们的”模块,而不是系统一。
对于这个示例,我创建了三个文件: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"]
这种方法有一个问题:如果你导入模块,它以某种方式位于上层文件夹中,它不会被检测到。
推荐阅读
- r - 基本问题:如何为绘图中的线条添加颜色
- django - 如何限制 django 频道房间中的客户端数量
- javascript - 如何为 Firebase DB 设置安全规则,以使用户无法向 DB 发出未经授权的请求?
- python - 如何在 Python 中检查大于 N 行的函数
- r - 使用 dplyr::filter() 删除 NA
- react-native - 返回按钮以纠正平面列表的位置
- google-sheets - 谷歌表格“如果”从列而不是单元格进行验证
- c++ - 我的 system() 命令给出了一些需要忽略的警告。如何隐藏警告?
- python - 'dict' 对象没有属性 '_committed' 谁能解释为什么会发生这个错误
- android - 在 Windows 10 上安装 Android Studio 时出现任何错误