python - 如何将模块导入到 Python 上导入的其他脚本中?

标签 python import module

我正在开发一个 Python 项目,其中使用不同的脚本。这里的问题是我不知道如何将模块导入到我导入的多个脚本中。例如:

#main.py
import os 
import script1
import script2

如何将 os 模块导入到所有其他脚本中,这样我就不必在 script1.py 和 script2.py 上再次导入 os

我是 Python 新手,谢谢

最佳答案

这确实不是一个好主意,因为它会使跟踪哪个模块(文件)需要哪个导入变得非常困难。但是,如果您必须这样做,则可以将文件中导入语句的数量减少到如下所示:

创建一个文件(例如,imports.py)并将所有导入内容放入其中:

import os 
import script1
import script2
# etc

然后,对于每个文件,您只需编写以下内容,而不是复制所有导入:

从导入导入*

..您将能够从该文件中使用它们。

值得注意的是,这样做实际上只会消除您在每个文件顶部写入导入的需要。 Python 已经确保在代码执行期间,每个模块仅导入一次,无论您在代码中包含该语句多少次。

根据documentation ,关于导入流程:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. [...] The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. [...] During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes.

如需进一步说明,用户 dim-an把它写得很好 this回答。

关于python - 如何将模块导入到 Python 上导入的其他脚本中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958944/

相关文章:

python - 使用重复嵌套模式从文本文件中提取文本

python - 网页抓取 : request not returning complete content of the webpage

java - 我可以将 eclipse 源文件夹转换为包吗?

python - 必须评估字符串才能从模块访问类

php - 如何做一个PHP钩子(Hook)系统?

node.js - 当需要 Node.js 中的模块时, 'dot slash' (./) 是强制性的吗?

javascript - Node - 工厂或构造函数,还是两者都不?

python - Datetime Unix 时间戳包含毫秒

python - 如何以嵌套字典格式对值进行排序?

python - 导入模块的开发版本而不是站 pip 包中安装的版本