Visual Studio Code was recently released and I liked the look of it and the features it offered, so I figured I would give it a go.
I downloaded the application from the downloads page, fired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Python code!
I really like the look and feel/usability/features of Visual Studio Code, but I can't seem to find out how to run my Python code, a real killer because that's what I program primarily in.
Is there is a way to execute Python code in Visual Studio Code?
30 Answers
There is a much easier way to run Python, and it doesn't need any configuration:
- Install the Code Runner Extension.
- Open the Python code file in Text Editor.
- To run Python code:
- use shortcut Ctrl + Alt + N
- or press F1 and then select/type Run Code,
- or right click the Text Editor and then click Run Code in the editor context menu
- or click the Run Code button in the editor title menu
- or click Run Code button in the context menu of file explorer
- To stop the running code:
- use shortcut Ctrl + Alt + M
- or press F1 and then select/type Stop Code Run
- or right click the Output Channel and then click Stop Code Run in the context menu
If you want to add the Python path, you could go to File → Preference → Settings, and add the Python path like below:
"code-runner.executorMap":
{
"python": "\"C:\\Program Files\\Python35\\python.exe\" -u"
}
In case you have installed the Python extension and manually set your interpreter already, you could configure your settings.json file as follows:
{
"python.pythonPath": "C:\\\\python36\\\\python36.exe",
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
}
}
Here is how to configure Task Runner in Visual Studio Code to run a .py file.
In your console, press Ctrl + Shift + P (Windows) or Cmd + Shift + P (Apple). This brings up a search box where you search for "Configure Task Runner"
If this is the first time you open the "Task: Configure Task Runner", you need to select "other" at the bottom of the next selection list.
This will bring up the properties which you can then change to suit your preference. In this case you want to change the following properties;
- Change the Command property from
"tsc"(TypeScript) to"Python" - Change showOutput from
"silent"to"Always" - Change
args(Arguments) from["Helloworld.ts"]to["${file}"](filename) - Delete the last property
problemMatcher - Save the changes made
You can now open your .py file and run it nicely with the shortcut Ctrl + Shift + B (Windows) or Cmd + Shift + B (Apple).
All these answers are obsolete now.
Currently you have to:
- install the Python language extension (and Python, obviously)
- open folder (important!), open any Python file inside that folder
- switch to debug "tab"(?) and click on the gearbox (with hint 'Configure of Fix 'launch.json'')
- save the opened launch.json file (it's placed in .vscode subdirectory in the folder opened in step #2)
- finally, click the green triangle or hit F5
No additional extensions or manual launch.json editing is required now.
You can add a custom task to do this. Here is a basic custom task for Python.
{
"version": "0.1.0",
"command": "c:\\Python34\\python",
"args": ["app.py"],
"problemMatcher": {
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*)+s$",
"message": 1
}
}
}
You add this to file tasks.json and press Ctrl + Shift + B to run it.
To extend vlad2135's answer (read his first); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).
Basically, when you click the gear icon, it creates a launch.json file in your .vscode directory in your workspace. You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting. Here's an example file:
You'll notice something cool after you generate it. It automatically created a bunch of configurations (most of mine are cut off; just scroll to see them all) with different settings and extra features for different libraries or environments (like Django).
The one you'll probably end up using the most is Python; which is a plain (in my case C)Python debugger and is easiest to work with settings wise.
I'll make a short walkthrough of the JSON attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.
- name: The name of the configuration. A useful example of why you would change it is if you have two Python configurations which use the same type of config, but different arguments. It's what shows up in the box you see on the top left (my box says "python" since I'm using the default Python configuration).
- type: Interpreter type. You generally don't want to change this one.
- request: How you want to run your code, and you generally don't want to change this one either. Default value is
"launch", but changing it to"attach"allows the debugger to attach to an already running Python process. Instead of changing it, add a configuration of type attach and use that. - stopOnEntry: Python debuggers like to have an invisible break-point when you start the program so you can see the entry-point file and where your first line of active code is. It drives some C#/Java programmers like me insane.
falseif you don't want it,trueotherwise. - pythonPath: The path to your install of Python. The default value gets the extension level default in the user/workspace settings. Change it here if you want to have different Pythons for different debug processes. Change it in workspace settings if you want to change it for all debug processes set to the default configuration in a project. Change it in user setting to change where the extension finds Pythons across all projects. (4/12/2017 The following was fixed in extension version 0.6.1).
Ironically enough, this gets auto-generated wrong. It auto-generates to "${config.python.pythonPath}" which is deprecated in the newer Visual Studio Code versions. It might still work, but you should use "${config:python.pythonPath}" instead for your default first python on your path or Visual Studio Code settings. (4/6/2017 Edit: This should be fixed in the next release. The team committed the fix a few days ago.) - program: The initial file that you debugger starts up when you hit run.
"${workspaceRoot}"is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder). Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to"${file}"which will start debugging at the file you have open and in focus in the moment you hit debug. - cwd: The current working directory folder of the project you're running. Usually you'll just want to leave this
"${workspaceRoot}". - debugOptions: Some debugger flags. The ones in the picture are default flags, you can find more flags in the python debugger pages, I'm sure.
- args: This isn't actually a default configuration setting, but a useful one nonetheless (and probably what the OP was asking about). These are the command line arguments that you pass in to your program. The debugger passes these in as though they you had typed:
python file.py [args]into your terminal; passing each JSON string in the list to the program in order.
You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.
You can go here for the extension's own documentation on launch options, with both optional and required attributes.
You can click the Add Configuration button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.
Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.
Pro tip: Different people on your team use different IDEs and they probably don't need your configuration files. Visual Studio Code nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add directory .vscode/ to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)!
There is a Run Python File in Terminal command available in the Python for Visual Studio Code extension.
As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.
So there are four ways to run Python in Visual Studio Code so far:
- Via an integrated terminal (come on, it's integrated! So technically you run it from within Visual Studio Code ;)
- No need to install any extension.
- No need to create and configure anything (assuming that you already have
pythonin your$PATH). ⌃Space(open terminal) andpython my_file.py(run file).
- Via custom Task (accepted Fenton's answer):
- No need to install any extension.
- Default Visual Studio Code's way of doing things.
- Beware not to copy-paste the answer because its
problemMatcher.pattern.regexpis broken and it hangs the editor. It's better to either deleteproblemMatcheror change theregexpto at least^\\s+(.*)$.
- Via Code Runner extension (@JanHan's answer):
- Need to configure
code-runner.executorMapin User Settings (add path to yourpython). - Very helpful extension especially if you run not only Python in Visual Studio Code.
- Via Microsoft's official Python extension (vlad2135's answer):
- Need to create
launch.js(a couple of clicks in Visual Studio Code's Debug tab). - The extension is a must-have for those who wants to use Visual Studio Code as a primary IDE for Python.
Install the Python extension (Python should be installed in your system). To install the Python Extension, press Ctrl + Shift + X and then type 'python' and enter. Install the extension.
Open the file containing Python code. Yes! A .py file.
Now to run the .py code, simply right click on the editor screen and hit 'Run Python File in the Terminal'. That's it!
Now this is the additional step. Actually I got irritated by clicking again and again, so I set up the keyboard shortcut.
- Hit that Settings-type-looking-like icon on bottom-left side → Keyboard Shortcuts → type 'Run Python File in the Terminal'. Now you will see that + sign, go choose your shortcut. You're done!
There is a lot of confusion around Visual Studio Code tasks and the debugger. Let's discuss about it first so that we understand when to use tasks and when to use the debugger.
Tasks
The official documentation says -
Lots of tools exist to automate tasks like linting, building, packaging, testing, or deploying software systems. Examples include the TypeScript Compiler, linters like ESLint and TSLint as well as build systems like Make, Ant, Gulp, Jake, Rake, and MSBuild.
.... Tasks in VS Code can be configured to run scripts and start processes so that many of these existing tools can be used from within VS Code without having to enter a command line or write new code.
So, tasks are not for debugging, compiling or executing our programs.