Where is Python's sys.path Initialized From?
Python meticulously crafts sys.path to provide a robust search path for modules and packages. The initialization process involves various steps and considerations.
Steps to Determine sys.path:
-
Determine sys.executable: Python identifies its absolute path from the operating system. This path becomes sys.executable.
-
Establish sys.exec_prefix and sys.prefix:
- Check for pyvenv.cfg in the same or parent directory of sys.executable.
- Use the configured home value or the directory of sys.executable as sys.prefix.
- Examine the PYTHONHOME environment variable.
- Search for landmark files (e.g., lib/python/os.py) to determine sys.exec_prefix and sys.prefix.
-
Configure sys.path:
- Add the script directory to sys.path (on Linux/Mac).
- Include contents of PYTHONPATH.
- Add the Python zip file.
- Include paths from relevant registry keys (Windows only, unless applocal = true in pyvenv.cfg).
-
Compile-time and Dynamic Values:
- Add paths specified in the PYTHONPATH macro (relative to sys.prefix).
- Include sys.exec_prefix (in Linux/Mac) or sys.prefix directory (in Windows).
-
Fallback Prefix Determination:
- If sys.prefix could not be determined, search for it dynamically within sys.path.
-
Site Package Import:
- Import the site module, which further populates sys.path based on sys.prefix and sys.exec_prefix.
The above is the detailed content of How is Python\'s `sys.path` Initialized?. For more information, please follow other related articles on the PHP Chinese website!