Configure Python Venv in VS Code Integrated Terminal Code Runner

Abstract: Fix Code Runner using the wrong Python interpreter by configuring the executor map to point to the virtual environment binary.

Created: 2026-08-05 by
To resolve Python virtual environment issues in VS Code's integrated terminal with Code Runner, you must ensure the extension uses the correct interpreter path. This is achieved by setting the python.pythonPath in your workspace settings to point directly to the bin/python executable inside your venv directory.

Understanding the Root Cause

The primary reason Code Runner fails to recognize your virtual environment is that it often defaults to the system-wide Python installation or the first available interpreter on your system PATH. When you activate a virtual environment manually in the terminal, your shell session updates the PYTHONPATH and executable locations. However, Code Runner operates independently of the terminal's active state for each execution. It spawns a new process to run your code, which does not inherit the activation context unless explicitly configured.

This disconnect leads to common symptoms such as missing module errors (e.g., ModuleNotFoundError: No module named 'requests') even though you have installed packages in your virtual environment. The solution lies in decoupling the dependency from the terminal session and hardcoding the interpreter location into the editor's configuration. By doing so, every time you press the play button, Code Runner invokes the specific Python binary associated with your project's isolated environment.

Locating Your Virtual Environment Path

Before modifying settings, you need the absolute path to the Python executable within your virtual environment. This path varies depending on your operating system and how you created the venv.

  • On Windows: Navigate to your project folder. Inside the virtual environment directory (commonly named venv or .venv), go to Scripts. The executable is typically python.exe.
  • On macOS and Linux: Go to your project folder, then into the virtual environment directory, followed by bin. The executable is python3 or python.

For example, if your project is located at /Users/name/myproject and your venv is named myenv, the path would be /Users/name/myproject/myenv/bin/python3. On Windows, it might look like C:\Users\name\myproject\myenv\Scripts\python.exe. Ensure you copy this exact path, as relative paths can sometimes cause resolution issues depending on where VS Code launches the process.

Configuring VS Code Settings

Once you have the correct path, you need to instruct Code Runner to use it. Open VS Code and access the user or workspace settings. It is highly recommended to configure this at the workspace level rather than the user level, ensuring that other projects are not affected by this specific virtual environment configuration.

  1. Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and select Preferences: Open Workspace Settings (JSON).
  2. Add or modify the following entry in the JSON object:
"code-runner.executorMap": {
    "python": "/absolute/path/to/your/venv/bin/python"
}

Replace the placeholder with the actual path you identified in the previous step. For instance:

"code-runner.executorMap": {
    "python": "/Users/jdoe/project/venv/bin/python3"
}

If you are using Windows, remember to escape backslashes or use forward slashes:

"code-runner.executorMap": {
    "python": "C:/Users/jdoe/project/venv/Scripts/python.exe"
}

Save the file. The next time you run a Python script via Code Runner, it will execute using the specified interpreter, granting access to all installed packages within that virtual environment.

Alternative: Using the Default Interpreter Setting

In some cases, simply setting the executor map may not be sufficient if other extensions interfere. A more robust approach involves telling VS Code itself which interpreter to use, which Code Runner often respects if configured correctly. You can set the default Python interpreter for the workspace by selecting the interpreter via the command palette.

Select Python: Select Interpreter from the command palette. Choose the interpreter located in your virtual environment. Once selected, verify that the status bar in the bottom right corner displays the correct path. While Code Runner has its own executorMap, aligning the general VS Code Python context helps prevent conflicts with IntelliSense and debugging tools. If you encounter issues where the change doesn't take effect immediately, restart the VS Code window to clear any cached states.

Troubleshooting Common Issues

If you have configured the path but still face errors, consider the following checks. First, verify that the path is correct by opening a terminal in VS Code and running which python (macOS/Linux) or where python (Windows) to see if it matches your configured path. Second, ensure that no other settings in settings.json are overriding the executor map. Look for keys like code-runner.runInTerminal; setting this to true forces Code Runner to run in the integrated terminal, which might pick up the activated environment if you manually activate it before running, but this is less reliable than the direct path method.

Additionally, check for syntax errors in your settings.json file. A missing comma or an unclosed bracket will cause VS Code to ignore the entire file, reverting to defaults. You can validate the JSON structure by hovering over the error indicator in the editor. If you recently updated VS Code or the Code Runner extension, ensure that your configuration syntax is compatible with the current version, as older configurations might use deprecated keys.

For related issues regarding kernel selection in newer VS Code versions, you may find helpful insights in our guide on Fixing 'Select Kernel' Problem in VS Code, although this primarily affects Jupyter notebooks, the underlying interpreter selection logic shares similarities.

Frequently Asked Questions

Why do I get ModuleNotFoundError after configuring the venv?

This usually means the path in your settings is incorrect or points to a different Python installation. Verify that the packages are actually installed in the target virtual environment by activating it manually and running pip list. Ensure the path in settings.json matches the Python binary of that specific environment exactly.

Can I use a relative path instead of an absolute path?

While possible, relative paths are risky because Code Runner may launch from different working directories depending on the file opened. Absolute paths guarantee consistency across all files in your project. If you must use relative paths, ensure they are resolved from the workspace root, but absolute paths are strongly recommended for stability.

Does this configuration affect debugging?

No, configuring Code Runner's executor map does not automatically update the Python debugger configuration. Debugging uses separate settings defined in launch.json. You should configure your debugger to use the same virtual environment interpreter to ensure breakpoints and variable inspection work correctly within the isolated environment.

What if I switch virtual environments frequently?

You will need to update the settings.json file each time you switch environments. Alternatively, you can use VS Code's built-in interpreter selector (Python: Select Interpreter) and ensure Code Runner is configured to respect the workspace interpreter, though manual executorMap updates remain the most reliable method for Code Runner specifically.

Is there a way to avoid editing settings.json manually?

You can edit settings via the GUI by searching for code-runner.executorMap in the Settings tab. However, the GUI interface for complex maps like executorMap can be cumbersome. Editing the JSON file directly provides better visibility and control over the exact string values being passed to the runner.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More