Reputation: 5159
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?
Upvotes: 288
Views: 833918
Reputation: 250922
You can add a custom task to do this. Here is a basic custom task for Python, add this to file tasks.json
and press Ctrl + Shift + B to run it.
{
"version": "0.1.0",
"command": "c:\\Python34\\python",
"args": [
"app.py"
],
"problemMatcher": {
"fileLocation": [
"relative",
"${workspaceRoot}"
],
"pattern": {
"regexp": "^(.*)+s$",
"message": 1
}
}
}
Upvotes: 79
Reputation: 47
Check the 'Run In Terminal' in the Code Runner Settings. This is the simplest solution.
Upvotes: 0
Reputation: 1456
Here's the current (September 2018) extensions for running Python code:
Official Python extension: This is a must install.
Jupyter: A extension for running Jupyter notebooks. This is a must install if you are a data scientist.
Code Runner: Incredibly useful for all sorts of languages, not just Python. I would highly recommend 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 code in there and not have to install any extensions.
Upvotes: 7
Reputation: 4874
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 ;)
python
in your $PATH
).⌃Space
(open terminal) and python my_file.py
(run file).Via custom Task (accepted Fenton's answer):
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+(.*)$
.Via Code Runner extension (@JanHan's answer):
code-runner.executorMap
in User Settings (add path to your python
).Via Microsoft's official Python extension (vlad2135's answer):
launch.js
(a couple of clicks in Visual Studio Code's Debug tab).Upvotes: 14
Reputation: 24201
Running the current python file as is does not have a keybinding associated by default, but you can set this with:
Upvotes: 10
Reputation: 51
If it is just a one file you want to run, make sure you have python installed on your system, then run
python <filename
Its just that simple
Upvotes: 0
Reputation: 11306
Upvotes: 0
Reputation: 13862
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.
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.
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 Visual Studio Code will try to debug your currently active file.
Press Ctrl + F5 and Visual Studio Code will ignore your breakpoints and run the code.
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 Visual Studio Code), use -
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
To run the code in an external terminal (outside of Visual Studio Code), use -
{
"name": "Python: Current File (External Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
}
N.B. If all documentation was easy to search and understand then we probably would not need Stack Overflow. Fortunately, the documentation I mentioned in this post is really easy to understand. Please feel free to read, ponder and enjoy.
Upvotes: 15
Reputation: 4941
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 the Python interpreter executable in your path):
I use Ctrl + Alt + N.
Upvotes: 10
Reputation: 931
To run python3 on windows vs code:
Download the python interpreter from their official site
Install the python packages for vs code. This can be installed directly from vscode's extension manager
Verify that your python3 has been installed by running this command:
py -3 --version
Run your script with the following command from vscode's terminal:
py -3 main.py
For more information, head over here for details installation procedure.
Upvotes: 1
Reputation: 1695
One workaround is to the following :
Upvotes: 0
Reputation: 91
Upvotes: 0
Reputation: 4243
I used my existing anaconda environment to run python. rather than using the python user appdata\local\programs\python use the anaconda install python by environment. This will give you access to all your libraries in the environment.
1. View->Command Palette->Open user settings
2. search python
a. Python: default interpreter path = c:\users\yourname\Anaconda3\python.exe
b. save the file
3. View->Command Palette->python:select interpreter
a. arrow down to your workspace name
b. select your python and environment
create a python script and run it.
see https://code.visualstudio.com/docs/python/environments
Upvotes: 0
Reputation: 1500
There is an easiest way to make a shortcut for run in terminal
command:
Keyboard Shortcuts
.python.execInTerminal
in search bar on top.Keybinding
column opposite the Python: Run Python File in Terminal
command and set the shortcut.Upvotes: 4
Reputation: 21144
If you install Python language extension for VSCode, it also installs Jupyter and Pylance by default, which lets you run Python code in interactive manner.
All you have to do is use # %%
before the code that you want to execute interactively.
As soon as you insert # %%
, you can see that VSCode creates a new Jupyter Cell for you.
And from there you can click on the Run Cell
cell menu and you can see the result.
So, all you have to do is type the following code in your VSCode,
# %%
text = 'Hello World from inline interactive Python'
print(text)
Upvotes: 2
Reputation: 384
Super simple:
Press the F5 key and the code will run.
If a breakpoint is set, pressing F5 will stop at the breakpoint and run the code in debug mode.
Other Method - To add Shortcut
Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.
Go to File → Preferences → Keyboard Shortcuts (alternatively, you can press Ctrl + K + S) In the search box, enter python.execInTerminal Double click that result (alternatively, you can click the plus icon) Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)
Now you can close the Keyboard Shortcuts tab Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it. The output will be shown in the bottom terminal tab.
Upvotes: 7
Reputation: 315
in new Version of VSCode (2019 and newer) We have run and debug Button for python,
Debug :F5
Run without Debug :Ctrl + F5
So you can change it by go to File > Preferences > Keyboard Shortcuts
search for RUN: start Without Debugging
and change Shortcut to what you want.
its so easy and work for Me (my VSCode Version is 1.51 but new update is available).
Upvotes: 7
Reputation: 342
Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.
python.execInTerminal
Upvotes: 5
Reputation: 131
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.
Upvotes: 3
Reputation: 28663
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).
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Main File",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/MyMain.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
Upvotes: 0
Reputation: 415
In the latest version (1.36) of Visual Studio Code (Python):
Press F5 and then hit Enter to run your code in the integrated terminal.
Ctrl + A and then hit Shift + Enter to run your code in the interactive IPython shell.
Upvotes: 9
Reputation: 169
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.
Upvotes: 16
Reputation: 39
From Extensions, install Code Runner. After that you can use the shortcuts to run your source code in Visual Studio Code.
First: To run code:
Second: To stop the running code:
Upvotes: 2
Reputation: 69
If you are running code and want to take input via running your program in the terminal, the best thing to do is to run it in terminal directly by just right click and choose "Run Python File in Terminal".
Upvotes: 2
Reputation: 28359
If you are using the latest version of Visual Studio Code (version 1.21.1). The task.json
format has changed, see here. So the answer by Fenton and by python_starter may no longer be valid.
Before you start configuring Visual Studio Code for running your Python file.
File -> Open Folder
to set your working folder).Now you can configure the task. The following steps will help you run your python file correctly:
task
, you will see a list of options, select Tasks: Configure Task
.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:
{
"version": "2.0.0",
"tasks": [
{
"label": "run this script",
"type": "shell",
"command": "python",
"args": [
"${file}"
],
"problemMatcher": []
}
]
}
In the above settings, you can give a meaningful label
to this task. For example, run python
.
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.For a more complete tutorial about task configuration, go to the Visual Studio Code official documentation.
Upvotes: 7
Reputation: 121
I had installed Python via Anaconda.
By starting Visual Studio Code via Anaconda I was able to run Python programs.
However, I couldn't find any shortcut way (hotkey) to directly run .py files.
(Using the latest version as of Feb 21st 2019 with the Python extension which came with Visual Studio Code. Link: Python extension for Visual Studio Code)
The following worked:
The below is similar to what @jdhao did.
This is what I did to get the hotkey:
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
}
}
]
}
Now every time that you press Ctrl + Shift + B, the Python file will automatically run and show you the output :)
Upvotes: 4
Reputation: 2232
In order to launch the current file with the respective venv, I added this to file launch.json
:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"pythonPath": "${workspaceFolder}/FOO/DIR/venv/bin/python3"
},
In the bin
folder resides the source .../venv/bin/activate
script which is regularly sourced when running from a regular terminal.
Upvotes: 0
Reputation: 315
As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.
Upvotes: 21
Reputation: 508
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.
"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.false
if you don't want it, true
otherwise."${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."${workspaceRoot}"
.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)!
Upvotes: 27