Python 导入迭代,sys.path

标签 python python-3.x import sys

所以我想知道,此时我正在阅读一本关于 Python 的书。本书解释如下:

The import algorithm

To truly understand namespace packages, we have to look under the hood to see how the import operation works in 3.3. During imports, Python still iterates over each directory in the module search path, sys.path, just as in 3.2 and earlier.

我的问题是:当未导入 sys 时,python 如何能够遍历 sys.path。此外,如果 python 能够看到 sys 而无需导入以遍历 sys.path 为什么我们需要在我们的代码中导入 sys

>>> sys
NameError: name 'sys' is not defined.

>>> import sys
>>> sys
<module 'sys' (built-in)>

最佳答案

没有矛盾。 Python 的 sys 模块 公开 修改 import 行为的搜索路径配置到 Python 端,但即使不导入 sys 在你的 Python 代码中,解释器知道它自己的配置。

在下面CPython source code有评论称

/* _PyMem_SetDefaultAllocator() is needed to get a known memory allocator,
   since Py_SetPath(), Py_SetPythonHome() and Py_SetProgramName() can be
   called before Py_Initialize() which can changes the memory allocator. */

这意味着 Py_SetPath() ,负责设置模块搜索路径,可以这么早执行,在任何 Python 代码可以被解释之前(例如,import 语句),它需要在解释器自己的内存分配器之前有自己的内存分配器内存分配器接管。

当 Python 解释器的 main() 函数运行时,it can already read使用 Py_GetPath() 的路径配置调用内部函数 _PyPathConfig_Init()如有必要,即使在解释器准备好执行 Python 代码之前,这样做也是安全的。

关于Python 导入迭代,sys.path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945739/

相关文章:

python - 永久升级 Google Cloud Shell 中的 Python 运行时?

python - 对图的顶点重新排序。它应该像彼得森图一样排序

python-3.x - NLTK-属性错误: module 'nltk' has no attribute 'data'

python - 如何绘制时间序列中事件的频率?

python - 检测 Python 程序何时退出或崩溃的好方法是什么?

python - 从物理公式(无数据文件)、python 和 numpy 绘制图形

python - 为什么 p 永远不会超过 2

python - 从字符串python中提取小时和分钟

javascript - 使用systemjs模块导入navigo

python - 在 Eclipse 中刷新 PyDev 导入路径