Tóm Tắt
Python with Visual Studio Code on macOS
Python is 3rd most loved/popular language in the survey of StackOverflow for the year 2018.
In this tutorial you use Python 3.x to create the simplest Python “Hello World” application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE.
Running Visual Studio Code on macOS
Installation
- Download Visual Studio Code for macOS.
- Double-click on the downloaded archive to expand the contents.
- Drag
Visual Studio Code.app
to theApplications
folder, making it available in theLaunchpad
.
Launching from the Command Line
You can also run VS Code from the terminal by typing ‘code’ after adding it to the path:
- Launch Visual Studio Code.
- Open the Command Palette (⇧⌘P) and type Install ‘code’ command in PATH command.
- Restart the terminal for the new
$PATH
value to take effect. You’ll be able to type ‘code .’ in any folder to start editing files in that folder.
Launch VS Code from terminal
Under the hood
Once you type Install ‘code’ command in PATH command in Command Palette, VS Code adds its path of executable in /Applications folder to PATH.
You can manually add VS Code to your path:
cat << EOF >> ~/.bash_profile
# Add Visual Studio Code (code)
export PATH="\$PATH:/Applications/Visual Studio Code.app/Contents/Resources/app/bin"
EOF
Getting Started with Python
Prerequisites
To successfully complete this tutorial, you must do the following:
- Install the Python extension.
Installing Python Extension
2. Install a version of Python 3.x. An installation through Homebrew on macOS using brew install python3
(the system install of Python 2.7 on macOS Sierra is not supported). If Python 3.x is already installed on your macOS, you can upgrade using brew upgrade python3
Python 3.x upgrade
Start VS Code in a project (workspace) folder
Create an empty folder called “helloPython”, navigate into it, and open VS Code (code
) in that folder (.
):
mkdir helloPython
cd helloPython
code .
VS Code created workspace
By starting VS Code in a folder, that folder becomes you “workspace”. VS Code stores settings that are specific to that workspace in .vscode/settings.json
, which are separate from user settings that are stored globally.
Select a Python interpreter
Python is an interpreted language, and in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.
From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
Select Python Environment in Status BarSelect Python 3 Interpreter in the Command Palette
Selecting an interpreter sets the python.pythonPath
value in your workspace settings to the path of the interpreter. To see the setting, select File > Preferences > Settings, then select the Workspace Settings tab.
Create a Python Hello World source code file
From the File Explorer toolbar, press the New File button on the helloPython
folder:
Click on new file icon
Name the file hello.py
, and it automatically opens in the editor:
VS Code interprets hello.py as Python
By using the .py
file extension, VS Code interprets this file as Python and evaluates the contents with the Python extension and the selected interpreter.
Next, start entering the following source code if using Python 3:
msg = "Hello World"
print(msg)
When you start typing print
, notice how IntelliSense presents auto-completion options.
IntelliSense presents auto-completion
IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg
variable contains a string, IntelliSense provides string methods then you type msg.
:
IntelliSense shows string methods on msg variable
Feel free to experiment with IntelliSense some more, but then revert changes so you have only the msg
variable and the print
call, and save the file (⌘S).
Run Hello World
It’s simple to run hello.py
with Python. Right-click in the editor and select Run Python File in Terminal(which saves the file automatically):
Runs hello.py in Terminal
The command opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py
:
Output of hello.py in terminal
There are other ways you can run Python within VS Code:
- Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is very convenient for testing just a part of a file.
Runs Selection/Line in Python Terminal
Run the debugger
Let’s now try debugging our simple Hello World program.
First, set a breakpoint on line 2 of hello.py
by placing the cursor on the print
call and pressing F9. Alternately, just click in the editor left gutter next to the line numbers. A red circle appears in the gutter.
Gutter in the editor left bar
Next, select the Debug View in the sidebar:
Debug View
Then select the settings icon on the debug toolbar (or use the Debug > Open configurations menu command):
Settings icon on the debug toolbar
The command opens a menu of available debuggers, which also shows Python & Python Experimental. Select Python.
Python debuggers
The Python extension then creates a launch.json
file that contains a number of configurations, which appear in the configurations drop-down; launch.json
is the standard name for a file containing debugging configurations:
launch.json of Python file
Select “Python: Current File”, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.
To automatically stop the debugger on the first line when the program starts, add a "stopOnEntry": true
setting to the “Python: Current File” configuration in launch.json
, so that the whole configuration appears as follows:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"stopOnEntry": true
},
Save launch.json
, switch to hello.py
in the editor, then run the debugger by selecting the green arrow in the Debug toolbar or pressing F5. Switching to hello.py
in the editor is the key. If you’re still in launch.json
& press F5, compiler will return error of invalid attributes in launch.jsonb
because it tries to run launch.json
as current file. BecausestopOnEntry
is set to true, the debugger stops on the first line of the file. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you see that only automatic dunder variables are defined:
Debugger stops
A debug toolbar appears along the top with the following commands from left to right: run (F5), step over (F10), step into (F11), step out (⇧F11), restart (⇧⌘F5), and stop (⇧F5).
Debug toolbar
The Status Bar also changes color (orange in many themes) to indicate debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run along with program output.
To continue running the program, select the run command on the debug toolbar (F5) or the green arrow in the Debug view. The debugger runs the program to the next breakpoint. The now-defined msg
variable appears in the Local pane
variables appear in Local pane
You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the … menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:
msg
msg.capitalize()
msg.split()
Debug Console
Select the green arrow or the run command on the debug toolbar (F5) again to run the program to completion. “Hello World” appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.
Output of the program
As always, any feedback is appreciated, so feel free to comment down here or reach out on twitter — and, as always,