Introduction
If your Python script does not run in VS Code, you may see errors such as "Python not found"
, "ModuleNotFoundError"
, or no output at all. This guide will help you troubleshoot and fix common issues that prevent Python scripts from running.
Step 1: Ensure Python Is Installed and Configured
- Open a terminal and check if Python is installed:
python --version
- If you see an error, install Python from python.org and restart VS Code.
- Ensure that Python is added to the system
PATH
by checking:where python # Windows which python # macOS/Linux
Step 2: Select the Correct Python Interpreter in VS Code
- Press
Ctrl + Shift + P
(Windows/Linux) orCmd + Shift + P
(macOS) to open the Command Palette. - Type “Python: Select Interpreter” and press
Enter
. - Choose the correct Python version that matches your project’s environment.
Step 3: Run the Script Using the Correct Terminal
- Ensure you’re running the script from the correct directory.
- Navigate to the script’s location in the terminal:
cd path/to/your/script
- Run the script using:
python script.py
- If you’re using a virtual environment, activate it first:
# Windows (Command Prompt) venv\Scripts\activate # macOS/Linux source venv/bin/activate
Step 4: Check for Syntax Errors or Missing Modules
- Ensure your script does not have syntax errors by running:
python -m py_compile script.py
- If you see a
ModuleNotFoundError
, install missing dependencies:pip install required-package
Step 5: Use the Run Button in VS Code
- Open the script in VS Code.
- Click the Run ▶ button in the top-right corner.
- Ensure “Python File” is selected as the execution option.
Step 6: Reload VS Code and Check for Extension Conflicts
- Press
Ctrl + Shift + P
and select “Reload Window”. - Disable extensions that might interfere with Python execution (e.g., conflicting terminal or linting extensions).
Final Thoughts
If your Python script is not running in VS Code, ensure Python is installed, the correct interpreter is selected, and the script runs in the right directory. Debugging using syntax checks and the VS Code Run button can also help resolve issues.
Next Step: Learn how to fix incorrect Python versions in the VS Code terminal: Why Is My VS Code Terminal Showing the Wrong Python Version?