Where is Python's sys.path Initialized From?
Python's sys.path, which contains the directories where Python searches for modules to import, undergoes a complex initialization process to determine its initial values. Here's a breakdown of how it's set up:
sys.executable Determination
- Python locates its physical location on the filesystem and uses it as the value for sys.executable.
sys.exec_prefix and sys.prefix Initialization
sys.path Initialization
- Python adds the directory of the script being executed to sys.path.
- On Linux/Mac, it adds the PYTHONPATH environment variable, if set.
- It includes the zip file path (/lib/python35.zip or path/to/python.zip).
- On Windows and without "applocal = true" in pyvenv.cfg, it adds subkeys from "HK_CURRENT_USERSoftwarePythonPythonCorePythonPath."
- On Windows and without "applocal = true" in pyvenv.cfg, and if sys.prefix was not found, it adds the "core contents" of "HK_CURRENT_USERSoftwarePythonPythonCorePythonPath."
- On Windows and without "applocal = true" in pyvenv.cfg, it adds subkeys from "HK_LOCAL_MACHINESoftwarePythonPythonCorePythonPath."
- On Windows and without "applocal = true" in pyvenv.cfg, and if sys.prefix was not found, it adds the "core contents" of "HK_LOCAL_MACHINESoftwarePythonPythonCorePythonPath."
- On Windows and with PYTHONPATH not set, prefix not found, and no registry keys present, it adds the relative compile-time value of PYTHONPATH.
- It incorporates paths in the PYTHONPATH compile-time macro relative to the dynamically-found sys.prefix.
- On Linux/Mac, it adds sys.exec_prefix. On Windows, it adds the directory used to search for sys.prefix.
- On Windows and without "applocal = true" in pyvenv.cfg, it attempts to find sys.prefix by locating landmark files in sys.path. If unsuccessful, it leaves sys.prefix blank.
Additional Modification by the Site Module
- The site module further modifies sys.path by adding directories based on sys.prefix, sys.exec_prefix, and platform-specific paths.
- It inspects these new paths for configuration files, potentially adding more paths.
The above is the detailed content of How does Python initialize the sys.path list?. For more information, please follow other related articles on the PHP Chinese website!