如何加载文件夹中的所有模块? [英] How to load all modules in a folder?

查看:52
本文介绍了如何加载文件夹中的所有模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能给我提供一种导入整个模块目录的好方法吗?
我有这样的结构:

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py

我尝试通过添加 __init__.py 并执行 from Foo import * 将其转换为包,但它没有按我希望的方式工作.

I tried just converting it to a package by adding __init__.py and doing from Foo import * but it didn't work the way I had hoped.

推荐答案

列出当前文件夹中的所有 python (.py) 文件,并将它们作为 __all__ 变量放入__init__.py

List all python (.py) files in the current folder and put them as __all__ variable in __init__.py

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

这篇关于如何加载文件夹中的所有模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆