### Python Version Output Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-windows-8.md Example output when verifying the Python installation. ```text Python 3.9.5 ``` -------------------------------- ### Get Pip Install Command for Module Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Translates a given product (e.g., pytest) into its corresponding module name for manual installation via pip. Provides an example of how to use this function. ```typescript import { IInstaller, Product } from '../common/types'; export function getPipInstallCommand(serviceContainer: IServiceContainer, product: Product): string { const installer = serviceContainer.get(IInstaller); const moduleName = installer.translateProductToModuleName(product); return `pip install ${moduleName}`; } // Usage const command = getPipInstallCommand(container, Product.pytest); console.log(command); // Output: pip install pytest ``` -------------------------------- ### Prompt User to Install a Product Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Use this method to show a user a prompt asking if they want to install a package. The installation proceeds if the user confirms. It returns the user's response and the action taken. ```typescript const installer = serviceContainer.get(IInstaller); const response = await installer.promptToInstall(Product.pytest); if (response === InstallerResponse.Installed) { console.log('pytest installed successfully'); } ``` -------------------------------- ### Getting the Active Python Environment Source: https://github.com/microsoft/vscode-python/blob/main/pythonExtensionApi/README.md This example demonstrates how to load the Python extension API and retrieve the path of the currently active Python environment. It also shows how to resolve the environment details. ```APIDOC ## Get Active Environment Path ### Description Retrieves the path of the active Python environment and resolves its details. ### Method `PythonExtension.api().environments.getActiveEnvironmentPath()` and `PythonExtension.api().environments.resolveEnvironment()` ### Parameters None ### Request Example ```typescript // Import the API import { PythonExtension } from '@vscode/python-extension'; // Load the Python extension API const pythonApi: PythonExtension = await PythonExtension.api(); // Get the active environment path const environmentPath = pythonApi.environments.getActiveEnvironmentPath(); // Resolve the environment details const environment = await pythonApi.environments.resolveEnvironment(environmentPath); if (environment) { // Use environment details, e.g., to run a script console.log('Environment resolved:', environment); } ``` ### Response #### Success Response - `environmentPath` (object): An object containing the path to the environment. - `environment` (object | null): An object with detailed environment information if resolved, otherwise null. ``` -------------------------------- ### promptToInstall Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Shows a prompt to the user asking if they want to install a package, and installs it if confirmed. Handles user responses like successful installation, disabled prompts, or ignoring the request. ```APIDOC ## promptToInstall ### Description Shows a prompt to user asking if they want to install a package, and installs if confirmed. ### Method ```typescript promptToInstall( product: Product, resource?: InterpreterUri, cancel?: CancellationToken, flags?: ModuleInstallFlags ): Promise ``` ### Parameters #### Path Parameters - **product** (Product) - Required - Package to install - **resource** (InterpreterUri) - Optional - File/folder to determine target interpreter - **cancel** (CancellationToken) - Optional - Cancellation token - **flags** (ModuleInstallFlags) - Optional - Installation flags ### Returns - `Promise` - User response and action taken ### Enum: InstallerResponse - `Installed` - Package was installed successfully - `Disabled` - User disabled installation prompts - `Ignore` - User chose to ignore this time ### Example ```typescript const installer = serviceContainer.get(IInstaller); const response = await installer.promptToInstall(Product.pytest); if (response === InstallerResponse.Installed) { console.log('pytest installed successfully'); } ``` ``` -------------------------------- ### Example: WindowsStoreLocator Implementation Source: https://github.com/microsoft/vscode-python/wiki/Interpreter-and-Environment-Discovery An example of extending `FSWatchingLocator` for the Windows Store environment. It demonstrates how to implement file system watching for a specific location. ```typescript export class WindowsStoreLocator extends FSWatchingLocator { protected readonly watchPaths: ReadonlyArray = [ "**/AppData/Local/Microsoft/WindowsApps/**", ]; constructor(workspace: WorkspaceFolder) { super(workspace); } public async getEnvs(): Promise { return []; } protected async onFileChanged(path: string): Promise { // No-op for now } } ``` -------------------------------- ### Check if a Product is Installed and Prompt if Not Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md This snippet first checks if a specified product is installed in the target interpreter. If it's not installed, it then prompts the user to install it. This is useful for ensuring a required package is available. ```typescript const installer = serviceContainer.get(IInstaller); const isPytestInstalled = await installer.isInstalled(Product.pytest); if (!isPytestInstalled) { await installer.promptToInstall(Product.pytest); } ``` -------------------------------- ### Pip Install Options Source: https://github.com/microsoft/vscode-python/blob/main/src/test/pipRequirements/example-requirements.txt Lists common command-line options for pip install that can be used within a requirements file. ```text --no-links ``` ```text -c constraints.txt ``` ```text -e git://git.myproject.org/MyProject#egg=MyProject ``` ```text FooProject >= 1.2 --global-option="--no-user-cfg" ``` -------------------------------- ### Installer Service Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/INDEX.md APIs for managing package installations within the Python extension. ```APIDOC ## Installer Service Service for installing and managing Python packages. ### Interface - `IInstaller`: The main interface for package installation operations. ### Operations - Package installation: Procedures for installing packages. - Version checking: How to check package versions. - Product types: Supported product types for installation. - Module mapping: Information on module to package mapping. ``` -------------------------------- ### InstallerResponse Enum Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Represents the possible outcomes of an installation prompt or process initiated by the installer service. ```APIDOC ## Enum: InstallerResponse ### Description Indicates the result of an installer operation or user interaction with installation prompts. ### Members - **Installed**: The package was successfully installed. - **Disabled**: The user has globally disabled installation prompts. - **Ignore**: The user chose to skip the installation for the current instance. ``` -------------------------------- ### install Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Installs a package without prompting the user, performing a silent installation. This method is useful for automated or background installations. ```APIDOC ## install ### Description Installs a package without prompting the user (silent installation). ### Method ```typescript install( product: Product, resource?: InterpreterUri, cancel?: CancellationToken, flags?: ModuleInstallFlags, options?: InstallOptions ): Promise ``` ### Parameters #### Path Parameters - **product** (Product) - Required - Package to install - **resource** (InterpreterUri) - Optional - File/folder to determine interpreter - **cancel** (CancellationToken) - Optional - Cancellation token - **flags** (ModuleInstallFlags) - Optional - Installation flags - **options** (InstallOptions) - Optional - Installation options ### Returns - `Promise` - Installation result ``` -------------------------------- ### Setup Repository with Nox (Linux/Mac) Source: https://github.com/microsoft/vscode-python/wiki/Coding Activate the virtual environment and use nox to set up the repository on Linux or macOS. ```shell source .venv/bin/activate .venv/bin/python -m pip install nox nox --session setup_repo ``` -------------------------------- ### Check Product Version Compatibility Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Verify if an installed package meets a specific semantic version requirement. This method returns the installation status, indicating if it's installed and meets the requirement, not installed, or installed but requires an upgrade. ```typescript const installer = serviceContainer.get(IInstaller); const status = await installer.isProductVersionCompatible(Product.pytest, '>=6.0.0'); if (status === ProductInstallStatus.NeedsUpgrade) { console.log('pytest needs to be upgraded'); } ``` -------------------------------- ### ProductInstallStatus Enum Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Defines the installation status of a product, indicating whether it is installed, not installed, or requires an update. ```APIDOC ## Enum: ProductInstallStatus ### Description Represents the current installation state of a product. ### Members - **Installed**: The package is installed and meets the required version criteria. - **NotInstalled**: The package is not currently installed. - **NeedsUpgrade**: The package is installed but is an older version and requires an upgrade. ``` -------------------------------- ### Get Conda System Information Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Fetches detailed information about the Conda installation and system. Returns Conda metadata or undefined if Conda is unavailable. ```typescript getCondaInfo(): Promise ``` -------------------------------- ### Usage Example for EnvironmentPath Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/environment-types.md Illustrates how to create an instance of the EnvironmentPath type. ```typescript const envPath: EnvironmentPath = { id: 'env-12345', path: '/home/user/.venv/bin/python' }; ``` -------------------------------- ### Install Development Module with Poetry Source: https://github.com/microsoft/vscode-python/wiki/Support-poetry-virtual-environments Installs a development tool or module into the Poetry environment using the `poetry add` command. Use `--allow-prereleases` for packages without stable releases. ```bash poetry add --dev ``` ```bash poetry add --dev --allow-prereleases ``` -------------------------------- ### Setup Repository with Nox (Windows PowerShell) Source: https://github.com/microsoft/vscode-python/wiki/Coding Activate the virtual environment and use nox to set up the repository on Windows using PowerShell. ```shell & ".venv/Scripts/Activate.ps1" .venv/Scripts/python -m pip install nox nox --session setup_repo ``` -------------------------------- ### Install VSCE Source: https://github.com/microsoft/vscode-python/wiki/Profiling Installs the VS Code extension packager globally. This is a prerequisite for packaging the extension. ```bash npm install -g vsce ``` -------------------------------- ### Example: WindowsRegistryLocator Implementation Source: https://github.com/microsoft/vscode-python/wiki/Interpreter-and-Environment-Discovery An example of extending the base `Locator` class for the Windows Registry environment. This locator does not require file system watching. ```typescript export class WindowsRegistryLocator extends Locator { constructor(workspace: WorkspaceFolder) { super(workspace); } public async getEnvs(): Promise { return []; } } ``` -------------------------------- ### InstallOptions Interface Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md An interface for defining package manager-specific installation options. ```APIDOC ## Interface: InstallOptions ### Description An interface that holds options specific to the installation process. The exact properties and their meanings depend on the context of the package manager being used. ### Definition ```typescript export interface InstallOptions { // Installation-specific options // Content depends on package manager context } ``` ``` -------------------------------- ### Example of Full Environment Structure Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/environment-types.md Demonstrates the instantiation of the Environment type with sample data, including executable, environment, and version details. ```typescript const env: Environment = { id: 'venv-abc123', path: '/project/.venv/bin/python', executable: { uri: Uri.file('/project/.venv/bin/python'), bitness: '64-bit', sysPrefix: '/project/.venv' }, environment: { type: 'VirtualEnvironment', name: 'myenv', folderUri: Uri.file('/project/.venv'), workspaceFolder: workspaceFolder }, version: { major: 3, minor: 11, micro: 5, release: { level: 'final', serial: 0 }, sysVersion: '3.11.5 (main, ...)' }, tools: ['Venv'] }; ``` -------------------------------- ### Environment Variables Example Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/environment-types.md An example demonstrating how to define and assign values to the EnvironmentVariables type, including a non-existent variable. ```typescript const vars: EnvironmentVariables = { 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin', 'PYTHONPATH': '/home/user/lib', 'NONEXISTENT': undefined }; ``` -------------------------------- ### Verify Python Installation Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-linux.md Use this command to confirm that Python was successfully installed on your Linux system. ```bash python3 --version ``` -------------------------------- ### ProductInstallStatus Enum Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/types.md Represents the installation status of a product. ```typescript export enum ProductInstallStatus { Installed, NotInstalled, NeedsUpgrade, } ``` -------------------------------- ### Install Python on Debian-based Linux Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-linux.md Run these commands in the terminal to install Python 3, the virtual environment module, and pip on Debian-based distributions. ```bash sudo apt-get update sudo apt-get install python3 python3-venv python3-pip ``` -------------------------------- ### InstallOptions Interface Definition Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md An interface for package manager-specific installation options. ```typescript export interface InstallOptions { // Installation-specific options // Content depends on package manager context } ``` -------------------------------- ### Package Extension Source: https://github.com/microsoft/vscode-python/wiki/Profiling Generates a .vsix file of your development bits for installation. This allows installing your extension without running the debugger. ```bash npm run package ``` -------------------------------- ### Install Python on Fedora-based Linux Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-linux.md Execute this command in the terminal to install Python 3 on Fedora-based distributions. ```bash sudo dnf install python3 ``` -------------------------------- ### Environment Markers Source: https://github.com/microsoft/vscode-python/blob/main/src/test/pipRequirements/example-requirements.txt Specifies how to conditionally install packages based on environment markers like Python version or operating system. ```text project;python_version>'3.0' ``` ```text project~=2.0.0;os_name=="linux" ``` -------------------------------- ### Discover Conda Installations and Environments Source: https://github.com/microsoft/vscode-python/wiki/Python-Environment-Search This pseudocode outlines the logic for discovering Conda installations and their environments. It involves checking known directories, parsing metadata files, and analyzing environment history. ```typescript // Step 1 // Get a list of all known directories where conda environments can be found // 1. environments.txt file // 2. .condarc file // 3. Other known locations // Step 2 // We hardcode some of the commonly known install directories of conda, miniconda, miniforge, etc for all platforms. for each known_install_folder in [/anaconda3, /miniconda3, etc]: conda_exe = `/bin/conda` (windows is slightly different) conda_version = `/conda_meta/conda-.json` python_exe = `/bin/python` (windows is slightly different) python_version = `/conda_meta/conda-.json` // Step 2.1 // We now have conda exe, version, default python information // Conda run command is computed as `[, run, -n, python]` for each env in `/envs`: // env is a conda environment // Find python exe and version in the conda-meta directory // If python is not found, then this is a conda env without Python. // These are named environments that are activated (run) using the `-n` option. // Previously we captured a list of all known conda envs // Go through those one by one and inspect the conda-meta/history file // And check whether that env was created by this current conda installation // If so, then associate that env with this conda installation // Next remove that env folder from the list captured in step 1. // Step 3 // Finally go through all of the remaining conda envs that were captured in step 1 // & did not get removed by step 2.1. // Go into the env folder one by one // Inspect the conda-meta/history file and try to find the installation location of the conda by parsing the `cmd:` line. // If we find a conda installation, then process that folder as we did inside step 2.1 ``` -------------------------------- ### Verify Python Installation Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-windows-8.md Run this command in a new terminal to check if Python is installed and to see its version. ```shell python --version ``` -------------------------------- ### InstallerResponse Enum Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/types.md Defines the possible responses from an installer operation. ```typescript export enum InstallerResponse { Installed, Disabled, Ignore, } ``` -------------------------------- ### Example ResolvedEnvironment Object Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/environment-types.md Illustrates a complete ResolvedEnvironment object, showing how all fields, including executable bitness, sysPrefix, and version details, are populated. ```typescript const resolved: ResolvedEnvironment = { id: 'venv-abc123', path: '/project/.venv/bin/python', executable: { uri: Uri.file('/project/.venv/bin/python'), bitness: '64-bit', // Always present sysPrefix: '/project/.venv' // Always present }, environment: { type: 'VirtualEnvironment', name: 'myenv', folderUri: Uri.file('/project/.venv'), workspaceFolder: undefined }, version: { major: 3, // Always a number minor: 11, micro: 5, release: { level: 'final', serial: 0 }, sysVersion: '3.11.5 (...)' // Always present }, tools: ['Venv'] }; ``` -------------------------------- ### Accessing Configuration Service Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/README.md Shows how to retrieve and use the configuration service to get Python extension settings. ```APIDOC ## Accessing Configuration Service ### Description Retrieve and utilize the `IConfigurationService` to access and monitor Python extension settings. ### Usage ```typescript import { IConfigurationService } from 'vscode-python'; const configService = serviceContainer.get(IConfigurationService); const settings = configService.getSettings(); console.log(`Python path: ${settings.pythonPath}`); console.log(`Linting enabled: ${settings.testing}`); // Listen for changes configService.onDidChange(() => { const newSettings = configService.getSettings(); console.log('Settings updated'); }); ``` ``` -------------------------------- ### Local File Path Requirements Source: https://github.com/microsoft/vscode-python/blob/main/src/test/pipRequirements/example-requirements.txt Specifies dependencies that should be installed from local file paths. ```text ./some/file ``` ```text some/file ``` -------------------------------- ### ProductInstallStatus Enum Definition Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Indicates the installation status of a product, including whether it needs an upgrade. ```typescript export enum ProductInstallStatus { Installed, NotInstalled, NeedsUpgrade } ``` -------------------------------- ### Get Conda Version Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Retrieves the version of the installed Conda. Returns the version as a SemVer object or undefined if unavailable. ```typescript getCondaVersion(): Promise ``` -------------------------------- ### Get Debugger Package Path Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/debug-api.md Retrieves the file system path to the debugpy package. Use this to directly invoke debugpy or verify its installation. ```typescript const pythonExt = await PythonExtension.api(); const debugpyPath = await pythonExt.debug.getDebuggerPackagePath(); if (debugpyPath) { console.log('Debugpy is available at:', debugpyPath); } else { console.log('Debugpy is not available or not yet installed'); } ``` ```typescript import * as fs from 'fs'; import * as path from 'path'; const pythonExt = await PythonExtension.api(); const debugpyPath = await pythonExt.debug.getDebuggerPackagePath(); if (debugpyPath && fs.existsSync(debugpyPath)) { const packageJson = path.join(debugpyPath, 'py.typed'); const isTyped = fs.existsSync(packageJson); console.log('Debugpy type hints available:', isTyped); } ``` ```typescript import * as path from 'path'; const pythonExt = await PythonExtension.api(); const debugpyPath = await pythonExt.debug.getDebuggerPackagePath(); if (debugpyPath) { // Extension path might contain version info const extensionPath = path.dirname(debugpyPath); // e.g., '/path/ms-python.debugpy-2024.0.0/pythonFiles/lib/debugpy' // Version: 2024.0.0 console.log('Debugpy path:', extensionPath); } ``` -------------------------------- ### Setup Repository with Nox (Linux/Mac PowerShell) Source: https://github.com/microsoft/vscode-python/wiki/Coding Activate the virtual environment and use nox to set up the repository on Linux or macOS using PowerShell. ```shell & ".venv/bin/Activate.ps1" .venv/bin/python -m pip install nox nox --session setup_repo ``` -------------------------------- ### Access Python Extension API Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/python-extension-api.md Use this method to get the Python extension API. It activates the extension if it's not already running. Ensure the extension is installed and enabled before calling. ```typescript import { PythonExtension } from 'vscode-python'; export async function activate(context: vscode.ExtensionContext) { try { const pythonExt = await PythonExtension.api(); await pythonExt.ready; console.log('Python extension ready'); } catch (error) { console.error('Python extension not available'); } } ``` -------------------------------- ### Clone Repository and Setup Virtual Environment Source: https://github.com/microsoft/vscode-python/wiki/Coding Clone the repository and set up a Python virtual environment. Activate the environment using the appropriate command for your shell. ```shell git clone https://github.com/microsoft/vscode-python cd vscode-python python3 -m venv .venv ``` -------------------------------- ### Ensure Pytest is Installed Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Checks if pytest is installed and prompts the user to install it if it's not. Handles different user responses to the installation prompt. ```typescript import { IInstaller, Product, InstallerResponse } from '../common/types'; import { IServiceContainer } from '../ioc/types'; export async function ensurePytestInstalled(serviceContainer: IServiceContainer) { const installer = serviceContainer.get(IInstaller); // Check if installed if (await installer.isInstalled(Product.pytest)) { console.log('pytest is already installed'); return; } // Prompt user to install const response = await installer.promptToInstall(Product.pytest); switch (response) { case InstallerResponse.Installed: console.log('pytest installed successfully'); break; case InstallerResponse.Disabled: console.log('User disabled installation prompts'); break; case InstallerResponse.Ignore: console.log('User chose not to install'); break; } } ``` -------------------------------- ### Install Python 3 using Homebrew Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/install-python-macos.md Use this command to install Python 3 if you have Homebrew package manager installed on your macOS system. ```bash brew install python3 ``` -------------------------------- ### initialize Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Initializes the interpreter service and sets up event listeners. ```APIDOC ## initialize ### Description Initializes the interpreter service and sets up event listeners. ### Signature ```typescript initialize(): void ``` ``` -------------------------------- ### Install Package for Specific Workspace Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Installs a specified package, such as pytest, for the Python interpreter associated with a particular workspace URI. Confirms successful installation. ```typescript import { IInstaller, Product, InstallerResponse } from '../common/types'; import { Uri } from 'vscode'; export async function installForWorkspace( serviceContainer: IServiceContainer, workspaceUri: Uri ) { const installer = serviceContainer.get(IInstaller); // Install pytest for this workspace's interpreter const response = await installer.install(Product.pytest, workspaceUri); if (response === InstallerResponse.Installed) { console.log('Package installed for workspace'); } } ``` -------------------------------- ### activate Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/extension-activation.md The main entry point for activating the Python extension. It initializes all extension components and returns the public API for other extensions to consume. ```APIDOC ## activate ### Description The main extension activation function called by VS Code when the Python extension is loaded. Initializes all extension components and returns the public API. ### Signature ```typescript export async function activate(context: IExtensionContext): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **context** (`IExtensionContext`) - Required - VS Code extension context containing subscriptions, storage, and workspace information ### Returns - `Promise` - The public Python extension API for use by other extensions ### Throws - Errors during activation are caught, logged, and sent as telemetry before being re-thrown - Extension will not be fully functional if activation fails ### Behavior 1. Initializes file logging 2. Sets up global services and dependency injection container 3. Activates experiment service to load experiment configuration 4. Initializes and activates components 5. Builds and returns the public API 6. Registers chat tools if applicable 7. Schedules post-activation tasks like interpreter refresh ### Request Example ```typescript import { PythonExtension } from './api/types'; // Called automatically by VS Code during extension activation export async function activate(context: IExtensionContext): Promise { // Extension initialization happens here // Returns API for other extensions to consume } // Usage by other extensions: const pythonExt = await PythonExtension.api(); const environments = pythonExt.environments.known; ``` ### Response #### Success Response (200) - **PythonExtension** - The public API object provided by the Python extension. ``` -------------------------------- ### Check Pytest Version Compatibility Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Verifies if pytest is installed and meets a specified version requirement. If not installed or needs an upgrade, it provides options to install or upgrade. ```typescript import { IInstaller, Product, ProductInstallStatus } from '../common/types'; export async function checkPytestVersion(serviceContainer: IServiceContainer) { const installer = serviceContainer.get(IInstaller); const status = await installer.isProductVersionCompatible(Product.pytest, '>=6.0.0'); switch (status) { case ProductInstallStatus.Installed: console.log('pytest is installed and meets version requirement'); break; case ProductInstallStatus.NotInstalled: console.log('pytest is not installed'); await installer.promptToInstall(Product.pytest); break; case ProductInstallStatus.NeedsUpgrade: console.log('pytest needs to be upgraded'); break; } } ``` -------------------------------- ### Installed Extensions Table Structure Source: https://github.com/microsoft/vscode-python/blob/main/resources/report_issue_user_data_template.md Template for listing installed extensions. This table structure is used to document the 'Extension Name', 'Extension Id', and 'Version' of each installed extension. ```markdown |Extension Name|Extension Id|Version| |---|---|---|{5} ``` -------------------------------- ### Configure unittest in settings.json Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Enable unittest and specify arguments for test discovery and verbosity. ```json { "python.testing.unittestEnabled": true, "python.testing.unittestArgs": [ "discover", "-s", "tests", "-p", "test_*.py", "-v" ] } ``` -------------------------------- ### Python Output Panel Example Source: https://github.com/microsoft/vscode-python/blob/main/resources/report_issue_template.md This is a placeholder for output from the Python Output panel. Users should replace 'XXX' with the actual output when reporting an issue. ```text XXX ``` -------------------------------- ### Product Enum Definition Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Defines the different types of products that can be installed or managed by the installer service. ```typescript export enum Product { pytest = 1, unittest = 12, tensorboard = 24, torchProfilerInstallName = 25, torchProfilerImportName = 26, pip = 27, ensurepip = 28, python = 29, } ``` -------------------------------- ### ITestConfigurationService.promptToEnableAndConfigureTestFramework Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Shows UI prompts to enable and configure a test framework for a workspace. ```APIDOC ## promptToEnableAndConfigureTestFramework ### Description Shows UI prompts to enable and configure a test framework for a workspace. ### Signature ```typescript promptToEnableAndConfigureTestFramework(wkspace: Uri): Promise ``` ### Parameters #### Path Parameters - **wkspace** (Uri) - Required - Workspace folder URI ### Returns - **Promise** - Completes when user finishes configuration ``` -------------------------------- ### isInstalled Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Checks if a specified package is currently installed in the target Python interpreter. Returns a boolean indicating the installation status. ```APIDOC ## isInstalled ### Description Checks if a package is installed in the target interpreter. ### Method ```typescript isInstalled(product: Product, resource?: InterpreterUri): Promise ``` ### Parameters #### Path Parameters - **product** (Product) - Required - Package to check - **resource** (InterpreterUri) - Optional - File/folder to determine interpreter ### Returns - `Promise` - True if package is installed ### Example ```typescript const installer = serviceContainer.get(IInstaller); const isPytestInstalled = await installer.isInstalled(Product.pytest); if (!isPytestInstalled) { await installer.promptToInstall(Product.pytest); } ``` ``` -------------------------------- ### URL Requirements Source: https://github.com/microsoft/vscode-python/blob/main/src/test/pipRequirements/example-requirements.txt Shows how to specify a dependency directly from a URL, typically pointing to a wheel file. ```text https://some-site.ca/project.whl ``` -------------------------------- ### Pyenv Directory Structure Analysis Source: https://github.com/microsoft/vscode-python/wiki/Python-Environment-Search This pseudocode outlines the logic for iterating through directories within a Pyenv installation to identify different types of Python environments. It checks for conda installations, extracts version information, and distinguishes between virtual environments (indicated by 'pyvenv.cfg') and regular Pyenv installations. ```typescript for each dir in pyenv directory: if dir is a conda installation folder: // Pass this onto the conda algorithm continue version = extract version from folder name env_path = the directory itself if /pyvenv.cfg exists: // This is a virtual env in pyenv else // This is a regulary pyenv installation ``` -------------------------------- ### Full Compile Command Source: https://github.com/microsoft/vscode-python/wiki/Coding Execute a full compilation of the extension from the command line. ```shell npx gulp prePublishNonBundle ``` -------------------------------- ### Example Multi-Project Workspace Structure Source: https://github.com/microsoft/vscode-python/wiki/Multi‐Project-Testing-in-VS-Code Illustrates a typical directory structure for a multi-project workspace containing distinct Python projects like a Django API, a shared library, and a data science project, each with its own pyproject.toml and virtual environment. ```tree my-workspace/ ├── backend/ # Django API project │ ├── pyproject.toml │ ├── tests/ │ └── .venv/ ├── frontend-utils/ # Shared utilities library │ ├── pyproject.toml │ ├── tests/ │ └── .venv/ └── ml-pipeline/ # Data science project ├── tests/ └── .venv/ ``` -------------------------------- ### enable Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Enables a specified test framework for a given directory. ```APIDOC ## enable ### Description Enables a test framework. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **testDirectory** (string | Uri) - Required - Directory to enable tests for - **product** (UnitTestProduct) - Required - Test framework ### Request Example None provided. ### Response #### Success Response - **void** - Operation completed successfully. #### Response Example None provided. ``` -------------------------------- ### Install Package in Activated Terminal Source: https://github.com/microsoft/vscode-python/blob/main/resources/walkthrough/environments-info.md Use this command to install a Python package into an activated virtual environment. Ensure the terminal is activated before running the command. ```bash python -m pip install numpy ``` -------------------------------- ### Product Enum Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Defines the different types of products that can be installed or managed by the installer service. This includes testing frameworks, package managers, and the Python interpreter itself. ```APIDOC ## Enum: Product ### Description An enumeration representing different installable products within the Python ecosystem. ### Members - **pytest** (1): Testing framework. - **unittest** (12): Testing framework. - **tensorboard** (24): Visualization toolkit. - **torchProfilerInstallName** (25): Name for PyTorch profiler installation. - **torchProfilerImportName** (26): Name for PyTorch profiler import. - **pip** (27): Package installer for Python. - **ensurepip** (28): Python module for bootstrapping pip. - **python** (29): The Python interpreter itself. ``` -------------------------------- ### Incremental Build Command Source: https://github.com/microsoft/vscode-python/wiki/Coding Run the incremental build process for the extension. ```shell npm run compile ``` -------------------------------- ### Translate Product Enum to Module Name Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/installer-service.md Converts a Product enum value into its corresponding Python module name, which is typically used for package installation commands like 'pip install'. ```typescript const installer = serviceContainer.get(IInstaller); const moduleName = installer.translateProductToModuleName(Product.pytest); console.log(`pip install ${moduleName}`); // Output: pip install pytest ``` -------------------------------- ### Listening to Configuration Changes Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/configuration-service.md Explains how to subscribe to configuration change events and react to updates, particularly those affecting Python settings. ```APIDOC ## Listening to Configuration Changes This section describes how to listen for configuration changes using the `onDidChange` event. ### Usage ```typescript configService.onDidChange((event) => { if (event === undefined || event.affectsConfiguration('python')) { // Re-read settings const newSettings = configService.getSettings(); console.log('Settings updated:', newSettings); } }); ``` ### Event Handler Signature `onDidChange(callback: (event: ConfigurationChangeEvent | undefined) => void): Disposable` ### Parameters - **callback** (function) - Required - A function to be called when configuration changes. It receives a `ConfigurationChangeEvent` object or `undefined`. ``` -------------------------------- ### getSettings Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/configuration-service.md Retrieves all Python extension settings for a given resource scope. If no resource is provided, it defaults to workspace settings. ```APIDOC ## getSettings ### Description Retrieves all Python extension settings for a given resource scope. ### Method ```typescript getSettings(resource?: Uri): IPythonSettings ``` ### Parameters #### Path Parameters - **resource** (Uri) - Optional - File or workspace folder URI to scope settings. If undefined, returns workspace settings ### Returns - `IPythonSettings` - Complete Python settings object ### Example ```typescript const configService = serviceContainer.get(IConfigurationService); // Get workspace settings const settings = configService.getSettings(); // Get settings for specific file const fileSettings = configService.getSettings(fileUri); console.log(`Python path: ${settings.pythonPath}`); console.log(`Test framework: ${settings.testing}`); ``` ``` -------------------------------- ### Windows Registry Python Environment Search Algorithm Source: https://github.com/microsoft/vscode-python/wiki/Python-Environment-Search This pseudo-code outlines the logic for finding Python installations registered in the Windows Registry under PythonCore and ContinuumAnalytics keys. It checks for installation paths and executable locations to identify valid environments. ```typescript for company of [PythonCore, ContinuumAnalytics]: for each key in [HKLM, HKCU]: for each installed_version in `/Software/Python/` // installed_version are values like 3.12, 3.10, 3.9, etc install_key = `/Software/Python//InstallPath` env_path = `install_key/(Default)` exe = `install_key/(ExecutablePath)` if company == PythonCore and `exe` exists on disc: version = `install_key/(Version)` // SysVersion contains only first 2 parts of version display_name = `install_key/(DisplayName)` 👍 track this environment else if company == ContinuumAnalytics and `exe` exists on disc: We treat this as a conda env 👍 Now use `conda` algorithm to get all conda environments under the directory `env_path`. ``` -------------------------------- ### Web Version Compilation Source: https://github.com/microsoft/vscode-python/wiki/Coding Command to build the web version of the extension. ```shell npx gulp webpack ``` -------------------------------- ### getCondaVersion Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Retrieves the currently installed version of Conda. ```APIDOC ## getCondaVersion ### Description Gets the Conda version. ### Method `getCondaVersion(): Promise` ### Returns - `Promise` - Conda version or undefined ``` -------------------------------- ### getActiveInterpreter Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Gets the currently active/selected interpreter for a resource. ```APIDOC ## getActiveInterpreter ### Description Gets the currently active/selected interpreter for a resource. ### Signature ```typescript getActiveInterpreter(resource?: Uri): Promise ``` ### Parameters #### Path Parameters - **resource** (Uri) - Optional - File or workspace folder to scope the query ### Returns - `Promise` - Active interpreter or undefined if not selected ### Example ```typescript const activeInterp = await interpreterService.getActiveInterpreter(); if (activeInterp) { console.log(`Active: ${activeInterp.path}`); } ``` ``` -------------------------------- ### isCondaAvailable Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Checks if Conda is installed and accessible in the current environment. ```APIDOC ## isCondaAvailable ### Description Checks if Conda is installed and available. ### Method `isCondaAvailable(): Promise` ### Returns - `Promise` - True if conda is installed and available ``` -------------------------------- ### Configure pytest in settings.json Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Enable pytest and specify arguments for test collection and reporting. ```json { "python.testing.pytestEnabled": true, "python.testing.pytestArgs": [ "tests", "-v", "--cov=src", "--cov-report=html", "--tb=short" ] } ``` -------------------------------- ### getCondaInfo Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Fetches comprehensive information about the Conda installation and environment. ```APIDOC ## getCondaInfo ### Description Gets conda system information. ### Method `getCondaInfo(): Promise` ### Returns - `Promise` - Conda metadata or undefined if conda unavailable ``` -------------------------------- ### Importing PythonExtension API Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/exports-index.md Demonstrates how to import and access the Python Extension API from an external extension. ```APIDOC ## Importing from Extension ### For External Extensions ```typescript import { PythonExtension } from 'vscode-python'; const api = await PythonExtension.api(); const ready = await api.ready; const environments = api.environments; ``` ``` -------------------------------- ### LaunchOptions Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Options for launching and executing tests. This includes working directory, arguments, test provider, and optional parameters for specific test runners like pytest. ```APIDOC ## LaunchOptions ### Description Options for launching and executing tests. This includes working directory, arguments, test provider, and optional parameters for specific test runners like pytest. ### Fields #### Required Fields - **cwd** (string) - Working directory for test execution - **args** (string[]) - Command-line arguments for test runner - **testProvider** (TestProvider) - Test framework (pytest, unittest) #### Optional Fields - **token** (CancellationToken) - Cancellation token - **outChannel** (OutputChannel) - Output channel for test output - **pytestPort** (string) - Port for pytest-specific communication - **pytestUUID** (string) - Unique ID for pytest session - **runTestIdsPort** (string) - Port for test ID runner - **project** (PythonProject) - Python project context ``` -------------------------------- ### Check Conda Availability Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/interpreter-service.md Determines if Conda is installed and accessible in the current environment. ```typescript isCondaAvailable(): Promise ``` -------------------------------- ### Configure Additional Virtual Environment Folders Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/configuration.md Provide additional directories to search for virtual environments beyond the default locations. ```json { "python.autoComplete.extraPaths": [ "${workspaceFolder}/src", "${workspaceFolder}/lib" ] } ``` -------------------------------- ### ITestConfigurationManager Source: https://github.com/microsoft/vscode-python/blob/main/_autodocs/api-reference/testing-api.md Provides methods to manage test framework configuration and setup for a workspace. ```APIDOC ## requiresUserToConfigure ### Description Checks if user needs to configure tests for workspace. ### Signature ```typescript requiresUserToConfigure(wkspace: Uri): Promise ``` ### Returns - `Promise` - True if configuration needed --- ## configure ### Description Guides user through test framework configuration. ### Signature ```typescript configure(wkspace: Uri): Promise ``` --- ## enable ### Description Enables the test framework. ### Signature ```typescript enable(): Promise ``` --- ## disable ### Description Disables the test framework. ### Signature ```typescript disable(): Promise ``` ```