How to Read the Python Path from VS Code settings.json in Python

This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 13 views 0 copies

Python code

26 lines
Python 3.9+
import json
from pathlib import Path
from unittest.mock import patch

def read_vscode_python_path(settings_path: Path) -> str:
    """Extract python.defaultInterpreterPath from VS Code settings.json."""
    with open(settings_path, "r") as f:
        settings = json.load(f)
    return settings.get("python", {}).get("defaultInterpreterPath", "not-set")

if __name__ == "__main__":
    mock_settings = Path("mock_settings.json")
    mock_settings.write_text(
        json.dumps({
            "python": {
                "defaultInterpreterPath": "/usr/bin/python3.11"
            }
        })
    )
    
    with patch("builtins.open", create=True) as mock_open:
        mock_open.return_value.__enter__.return_value.read.return_value = mock_settings.read_text()
        path = read_vscode_python_path(mock_settings)
    
    mock_settings.unlink()
    print(f"Python path from settings.json: {path}")

Output

stdout
Python path from settings.json: /usr/bin/python3.11

How it works

The read_vscode_python_path function opens the settings file, parses it with json.load, and then safely traverses nested dictionaries using .get() to avoid KeyError. The mock in the __main__ block patches builtins.open to simulate reading a file from disk without actually keeping a reference, demonstrating how you could test such a function. Real usage would simply pass the actual settings.json path from your .vscode folder.

Common mistakes

  • Forgetting to use `.get()` for nested keys, causing KeyError if the structure changes.
  • Passing a string path instead of a Path object and then relying on implicit conversion.
  • Mocking `open` incorrectly, such as not setting `__enter__` and `read` return values.

Variations

  1. Use `pathlib.Path.read_text()` and `json.loads` to simplify file handling without a context manager.
  2. Use `os.path.expanduser` to handle `~` in the path for cross-platform support.

Real-world use cases

  • Automating IDE configuration checks in CI to ensure correct Python interpreter is set.
  • Building a pre-commit hook that validates the interpreter path in developer settings files.
  • Synchronizing Python interpreter paths across multiple machines for team consistency.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.