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.
Does anyone know if there is a way to execute Python code in Visual Studio Code?
To extend @vlad2135’s answer (read his first); that is how you set up python debugging in VSCode with Don Jayamanne’s great python extension (Which is a pretty full featured IDE for python these days, and arguably one of VS code’s best language extensions IMO).
Basically when you click the gear icon, it creates a launch.json in your .vscode directory in your workspace. You can also make this yourself, but it’s probably just simpler to let VSCode 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 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 config).
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. false if you don’t want it, true otherwise.
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 config in a project. Change it in user setting to change where the extension finds python across all projects. (4/12/17 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 VSCode versions. It might still work, but you should use “${config:python.pythonPath}” instead for your default first python on your path or VS settings. (4/6/17 Edit: This should be fixed in the next release. The team commited 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 VSCode 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 IDE’s and they probably don’t need your configurations files. VSCode 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 .vscode/ to your .gitignore if this is your first time generating a VSCode file(This process will create the folder in your workspace if you don’t have it already)!
Beware not to copy-paste the answer because its problemMatcher.pattern.regexp is broken and it hangs the editor. It’s better to either delete problemMatcher or change the regexp to at least ^\\s+(.*)$.
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! .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 of clicking again and again so I setup 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!
Code Runner: Increadibly useful for all sorts of languages, not just python. Would highly reccomend installing.
AREPL: Real-time python scratchpad that displays your variables in a side window. I’m the creator of this so obviously I think it’s great but I can’t give a unbiased opinion ¯\_(ツ)_/¯
Wolf: Real-time python scratchpad that displays results inline
And of course if you use the integrated terminal you can run python in there and not have to install any extensions.
There is a lot of confusion around VSCode Tasks and Debugger. Let’s discuss about it first so that we understand when to use Tasks and when to use Debugger.
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.
Debugger
If we check the debugger documentation, we will find there is something called run mode. It says –
In addition to debugging a program, VS Code supports running the
program. The Debug: Start Without Debugging action is triggered with
Ctrl+F5 and uses the currently selected launch configuration. Many of
the launch configuration attributes are supported in ‘Run’ mode. VS
Code maintains a debug session while the program is running, and
pressing the Stop button terminates the program.
So, Press F5 and VS Code will try to debug your currently active file.
Press Ctrl+F5 and VSCode will ignore your breakpoints and run the code.
Configuring the Debugger
To configure the debugger, go through the documentation. In summary it says, you should modify the launch.json file. For starters, to run the code in integrated terminal (inside VS Code), use –
N.B. If all documentations were easy to search and understand then we probably would not need stackoverflow. Fortunately, The documentations I mentioned in this post are really easy to understand. Please feel free to read, ponder and enjoy.
If you are using the latest version of vs code (version 1.21.1). The task.json format has changed, see here. So the answer by @Fenton and @python_starter may no longer be valid.
Before starting configuration
Before you start configuring vs code for running your python file.
Make sure that you have installed Python and added its executable to your system PATH.
You must set the folder where your python source file resides as your working folder (go to File -> Open Folder to set your working folder).
Configuration steps
Now you can configure the task. The following steps will help you run your python file correctly:
use Ctrl+Shift+P and input task, you will see a list of options, select Tasks: Configure Task.
You will then be prompted create task.json from template, choose this option, and you will be prompted to choose from a list of options. Choose Others.
Then in the opened task.json file, use the following settings:
In the above settings, you can give a meaningful label to this task. For example, run python.
Go to the Tasks menu and click Run Task. You will be prompted to choose the task. Just choose the newly created run this script task. You will see the result in the TERMINAL tab.
A simple and direct Python extension would save both time and efforts.
Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe"
With above steps at least the basic Python programs can be executed.
If you are running a code and want to take input via running your program in the terminal. best thing to do is to run it in terminal directly by just right click and choose “Run python file in terminal”.
回答 17
从Extension安装Code Runner。之后,您可以使用快捷方式在Visual Studio Code中运行源代码。
I use Python 3.7 (32 bit). To run a program in Visual Studio Code, I right-click on the program and select “Run Current File in Python Interactive Window”. If you do not have Jupyter, you may be asked to install it.
If I just want to run the Python file in the terminal, I’ll make a keyboard shortcut for the command because there isn’t one by default (you need to have python in your path):
Go to Preferences -> Keyboard Shortcuts
Type ‘run python file in terminal’
Click on the ‘+’ for that command and enter your keyboard shortcut
{//See https://go.microsoft.com/fwlink/?LinkId=733558//for the documentation about the tasks.json format
"version":"2.0.0","tasks":[{"label":"Run Python File",//this is the label I gave
"type":"shell","command":"python","args":["${file}"]
保存后,文件更改为:
{//See https://go.microsoft.com/fwlink/?LinkId=733558//for the documentation about the tasks.json format
"version":"2.0.0","tasks":[{"label":"Run Python File","type":"shell","command":"python","args":["${file}"],"group":{"kind":"build","isDefault": true
}}]}
I had installed python via Anaconda.
By starting VS code via anaconda I was able to run python programs.
However, I couldn’t find any shortcut way (hotkey) to directly run .py files.
Right clicking and selecting ‘Run python file in terminal’ worked for me.
CTRL + A then SHIFT + ENTER (on windows)
The below is similar to what @jdhao did.
This is what I did to get the hotkey:
CTRL + SHIFT + B //run build task
It gives option to configure
I clicked on it to get more options. I clicked on Other config
A ‘tasks.json’ file opened
I made the code look like this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File", //this is the label I gave
"type": "shell",
"command": "python",
"args": ["${file}"]
After saving it, the file changed to this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File",
"type": "shell",
"command": "python",
"args": [
"${file}"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
After saving the file ‘tasks.json’, go to your python code and press
CTRL + SHIFT + B.
Then click on Run task -> Run Python File //this is the label that
you gave.
Now every time that you press CTRL + SHIFT + B, the python file will automatically run and show you the output :)
回答 21
为了使用相应的venv启动当前文件,我将其添加到 launch.json
{"name":"Python: Current File","type":"python","request":"launch","program":"${file}","pythonPath":"${workspaceFolder}/FOO/DIR/venv/bin/python3"},
{"version":"0.2.0","configurations":[{"name":"Python: Main File","type":"python","request":"launch","program":"${workspaceFolder}/MyMain.py","console":"integratedTerminal","cwd":"${workspaceFolder}"}]}
If you have a project consisting of multiple python files and you want to start running/debugging with the main program independent of which file is current you create the following launch configuration (change MyMain.py to your main file)