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.
Python code
26 linesimport 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
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
- Use `pathlib.Path.read_text()` and `json.loads` to simplify file handling without a context manager.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.