No1Lives4Ever
No1Lives4Ever

Reputation: 6883

Python and Visual Studio Code - How do I run a specific file in the editor?

I am writing a small application with Visual Studio Code and Python. My application has two files, Main.py and MyCustomClass.py. Main.py is the entry point to the application, MyCustomClass.py contains the logic code to solve some problems.

Currently, the debugger is set to run whatever the active file is. Is it possible to configure Visual Studio Code to run a specific file versus the active file in the editor?

Upvotes: 15

Views: 21045

Answers (2)

ZSvedic
ZSvedic

Reputation: 500

You need to edit your launch.json file. A quick way to do it is to click the wrench icon on the run toolbar:

Enter image description here


Then add the following to the launch.json file:

    {
        "name": "Python: main.py (Integrated Terminal)",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/main.py",
        "console": "integratedTerminal"
    },

Above is my configuration, and the "program" line is what does the magic.

Upvotes: 32

ScottB
ScottB

Reputation: 311

The program setting in your launch configuration settings refers to the Python script that will be executed. By default, it is set to ${file} which refers to the file you are actively editing. Just set the value to the file you want to run.

{
   "name": "Python",
   "type": "python",
   "request": "launch",
   "stopOnEntry": true,
   "pythonPath": "${config:python.pythonPath}",
   "program": "main.py",  // Specify the full path to your file
   "cwd": "${workspaceFolder}",
   "env": {},
   "envFile": "${workspaceFolder}/.env",
   "debugOptions": [
       "RedirectOutput"
   ]
},

I should mention that if you are using Windows you can use either forward slashes / or double back slashes \\ in the program path. Single back slashes won't work.

Upvotes: 16

Related Questions