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