Explain Codes LogoExplain Codes Logo

Find where python is installed (if it isn't default dir)

python
prompt-engineering
functions
venv
Nikita BarsukovbyNikita Barsukov·Feb 7, 2025
TLDR

Unix/Linux/Mac:

which python3

For Python 2.x:

which python

Windows:

where python

Using a Python script or interactive session:

import sys print(sys.executable)

These lines of code return the path to the Python executable or binary. The sys.executable command will give the full path inside any Python environment.

Advanced insights with the sys module

Beyond the Python executable, sys module returns more detailed information:

  • sys.exec_prefix provides the installation path of the standard libraries of Python.
  • sys.path contains all locations (directories) where python finds its modules.

Try this:

import sys print("Executable Path:", sys.executable) print("Standard Library:", sys.exec_prefix) print("Module Search Paths:", sys.path)

Note: The command-line tools like which or where can fail if Python's binary is not included in the system PATH.

Dealing with multiple Python installations

Python can pose a challenge when found in virtual environments or instances with multiple versions installed. Use these commands:

Unix/Linux/Mac:

type -a python3

This lists all locations for an executable named python3.

Windows: Using PowerShell:

Get-Command python | Select-Object -ExpandProperty Definition

For virtual environments, remember to enable it first. Then run sys.executable to get the accurate path.

source env/bin/activate python -c 'import sys; print(sys.executable)'

Common traps you might fall into

While locating Python installation there can be few common obstacles:

  • Python 2 vs Python 3: Your commands may end up returning the location of undesired version if both Python 2 and 3 are installed.
  • Different shells: Since different shells have different PATH configurations, your which or where output may vary.
  • Symbolic links: which can sometimes return a path that is a symbolic link, not the actual installation directory.

Expert level: Unmasking Python

The hidden corners of Python installations can be reached with some expert-level commands:

Absolute Pythonistic path

Readlink command for Unix users can help you unmask the symbolic links and determine the absolute path to the Python executable as follows:

readlink -f $(which python3)

Python and your shell

Bash users can find the history of executed python commands with:

history | grep python

PS: It's like going on a treasure hunt in your own terminal, who knows what you might find there!

Varsity vars

figuring out your environment variables can also provide some interesting clues. Specifically PATH, PYTHONHOME, and PYTHONPATH.

Try these:

printenv | grep PYTHON echo $PATH