Delving into sys.path Initialization in Python
Understanding the initialization process of Python's sys.path is crucial for comprehending Python's search path for modules. Despite the misconception that PYTHONPATH exclusively drives this initialization, Python's intricate algorithm factors in various other sources.
The following steps elucidate this process:
Initialization of sys.executable, sys.exec_prefix, and sys.prefix
- Python meticulously identifies its location based on the operating system's information, mirroring the path of the actual physical executable in sys.executable.
- A pyvenv.cfg file in the executable's directory or one level up holds configuration options influencing sys.prefix. Notably, the home configuration can override the default directory containing sys.executable.
- If the PYTHONHOME environment variable exists, it overrides the previously set sys.prefix and sys.exec_prefix values.
- Failing the above conditions, these values are derived by traversing backward from sys.executable, seeking symbolic links or landmark files to establish the directory and its prefix.
Determination of sys.path
Post-Initialization Actions
- The site module is loaded, dynamically adding paths based on sys.prefix and sys.exec_prefix.
- Configuration files are examined from within the added paths for further sys.path modifications.
Pitfalls and Important Notes
- Incorrectly setting home = in pyvenv.cfg can lead to a null sys.prefix value, causing a fallback to pre-compiled defaults.
- The presence of a PYTHONHOME environment variable can disrupt pyvenv.cfg settings on Linux and Mac.
- The absence of PYTHONHOME on Windows, along with a pyvenv.cfg lacking home = , may result in a fallback sys.prefix value.
- If sys.prefix remains unresolved during sys.path initialization, Windows embarks on a detailed search for landmark files to determine it.
The above is the detailed content of How Does Python Initialize sys.path?. For more information, please follow other related articles on the PHP Chinese website!