How do I find out my PYTHONPATH using Python?
Here's the one-liner to quickly view your Python module search path or PYTHONPATH
:
Note: This code presents the directories that Python trawls through hunting for modules - which effectively portrays your PYTHONPATH
.
Key concepts: PYTHONPATH and sys.path
PYTHONPATH
is an environment variable that holds a list of directories where Python should look for modules during imports. On launching a Python session, PYTHONPATH
directories get attached to a Python list known as sys.path
, which can be accessed using the sys
module.
Anatomy of sys.path
sys.path
is a composite list including:
- Directory containing the input script (or current directory if not specified).
- Directories in
PYTHONPATH
(if set). - Installation-dependent default directories.
Remember, sys.path
might have extra entries not explicitly set in PYTHONPATH
.
Direct access to PYTHONPATH
You can also get the PYTHONPATH
in your script through:
Note: It returns an empty string if PYTHONPATH
isn't set, saving you from pesky errors.
Modifying your Python paths
Augmenting PYTHONPATH from a shell
Expand your PYTHONPATH
from a shell using the export
command:
Altering sys.path within your Python script
At runtime, you can change sys.path
straight from your scripts:
Visualizing PYTHONPATH
Consider PYTHONPATH
as your GPS for Python modules. Python navigates through the directories from sys.path
looking for any module you request.
Each path functions like a specific address leading to the house of a Python module!
Operating over platforms and Python versions
Cross-platform access to PYTHONPATH
Access and manipulation methods for PYTHONPATH
offer universal compatibility, working across operating systems like Windows, macOS, and Linux.
Compatibility with multiple Python versions
Dealing with several Python versions on your system? Make sure you use python2
or python3
to specify the PYTHONPATH
for your preferred Python version.
Handling errors and environment
Dealing with an unset PYTHONPATH
If PYTHONPATH
isn't set, os.environ will throw a KeyError
. To handle this:
Caution while modifying sys.path
You can perform list operations on sys.path
rendering it dynamic but beware of module resolution conflicts due to reckless changes.
Taking it to the terminal
To get Python paths from the terminal, use this gem:
This command invokes Python and prints the module path in your terminal.
Was this article helpful?