在Python中导入模块的文件夹 [英] Import folder of modules in Python

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

问题描述

在python中是否可以从文件夹/包中获取模块列表并导入它们?

Is it possible in python to get a list of modules from a folder/package and import them?

我希望能够从一个函数中执行此操作在类中,以便整个类可以访问它们(可能从 __ init __ 方法完成)。

I would like to be able to do this from a function inside a class, so that the entire class has access to them (possibly done from the __init__ method).

任何帮助将不胜感激。

推荐答案

参见模块文档


唯一解决方案是让包作者提供包的显式
索引。 import语句使用以下
约定:如果包的 __ init __。py 代码定义名为
的列表 __ all __ ,它被视为遇到包import *时应导入的模块名称列表。
软件包作者可以在发布新版本的
软件包时保持此列表的最新状态。如果包装作者没有看到从包装中导入*的用途,也可以决定不支持
。对于
的例子,文件的声音/效果/ __ init __。py 可能包含以下代码的

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sounds/effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

这意味着从sound.effects import *将导入声音包的三个命名子模块。

This would mean that from sound.effects import * would import the three named submodules of the sound package.

是的,您可以通过为目录中的文件创建目录列表并手动导入它们来找到一种方法。但是你没有内置的语法。

Yes, you could find a way to do this by doing a directory listing for the files in the directory and import them manually. But there isn't built-in syntax for what you're asking.

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

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