在本教程中,您将使用Python 3在Visual Studio Code中创建最简单的Python“ Hello World”应用程序。通过使用Python扩展,您可以将VS Code变成一个功能强大的轻量级Python IDE(您可能会找到PyCharm的高效替代品)。
本教程向您介绍VS Code作为Python环境,主要介绍如何通过以下任务来编辑,运行和调试代码:
本教程无意教您Python本身。熟悉VS Code的基础知识之后,您可以在VS Code的上下文中遵循python.org上的任何编程教程,以对该语言进行介绍。
如果您有任何问题,请随时在VS Code文档库中提交本教程的问题。
注意:在本教程中,您可以将VS Code与Python 2结合使用,但是需要对代码进行适当的更改,此处不做介绍。
要成功完成本教程,您需要首先设置Python开发环境。具体来说,本教程要求:
如果尚未这样做,请安装VS Code。
接下来,从Visual Studio Marketplace 安装VS Code的Python扩展。有关安装扩展的更多详细信息,请参阅Extension Marketplace。Python扩展名为Python,由Microsoft发布。
与Python扩展一起,您需要安装Python解释器。您使用哪种口译员取决于您的特定需求,但是下面提供了一些指导。
从python.org安装Python。通常,您可以使用页面第一个出现的Download Python按钮下载最新版本。
注意:如果您没有管理员权限,则在Windows上安装Python的另一个选择是使用Microsoft Store。Microsoft Store提供了Python 3.7和Python 3.8的安装。请注意,使用此方法可能与某些软件包存在兼容性问题。
有关在Windows上使用Python的其他信息,请参阅Python.org上的在Windows上使用Python。
不支持在macOS上系统安装Python。相反,建议通过Homebrew安装。要在macOS上使用Homebrew安装Python brew install python3
,请在终端提示下使用。
注意在macOS上,请确保PATH环境变量中包含VS Code安装的位置。有关更多信息,请参见这些设置说明。
在Linux上的内置Python 3安装效果很好,但是要安装其他Python软件包,必须pip
使用get-pip.py进行安装。
数据科学:如果使用Python的主要目的是数据科学,那么您可以考虑从Anaconda下载。Anaconda不仅提供Python解释器,而且还提供许多有用的数据科学库和工具。
适用于Linux的Windows子系统:如果您正在Windows上工作,并且希望Linux环境可以与Python一起使用,那么可以选择适用于Linux的Windows子系统(WSL)。如果选择此选项,则还需要安装Remote-WSL扩展。有关将WSL与VS Code一起使用的更多信息,请参见VS Code远程开发或尝试“ 在WSL中使用”教程,该教程将引导您完成设置WSL,安装Python以及创建在WSL中运行的Hello World应用程序。
要验证您是否已在计算机上成功安装Python,请运行以下命令之一(取决于您的操作系统):
Linux / macOS:打开“终端窗口”并键入以下命令:
python3 --version
Windows:打开命令提示符并运行以下命令:
py -3 --version
如果安装成功,则输出窗口应显示您安装的Python版本。
注意可以
py -0
在VS Code集成终端中使用该命令来查看计算机上安装的python版本。默认解释器由星号(*)标识。
使用命令提示符或终端,创建一个名为“ hello”的空文件夹,导航至该文件夹,然后通过输入以下命令code
在该文件夹(.
)中打开VS Code():
mkdir hellocd hellocode .
注意:如果您使用的是Anaconda发行版,请确保使用Anaconda命令提示符。
通过在文件夹中启动VS Code,该文件夹将成为您的“工作区”。VS Code将特定于该工作空间的.vscode/settings.json
设置存储在中,这些设置与全局存储的用户设置分开。
或者,您可以通过操作系统UI运行VS Code,然后使用“ 文件”>“打开文件夹”打开项目文件夹。
Python是一种解释型语言,要运行Python代码并获得Python IntelliSense,必须告诉VS Code使用哪个解释器。
在VS Code中,通过打开命令面板(Ctrl + Shift + P)选择一个Python 3解释器,开始键入Python:选择要解释的解释器命令,然后选择该命令。如果可用,您还可以使用状态栏上的“ 选择Python环境”选项(它可能已经显示了选定的解释器):
该命令显示了VS Code可以自动找到的可用解释器的列表,包括虚拟环境。如果看不到所需的解释器,请参阅“ 配置Python环境”。
注:当使用蟒蛇分布,正确的解释应该有后缀
('base':conda)
,例如Python 3.7.3 64-bit ('base':conda)
。
选择解释器会将python.pythonPath
工作空间设置中的值设置为解释器的路径。要查看设置,请选择文件 > 首选项 > 设置(在macOS上为代码 > 首选项 > 设置),然后选择工作区设置选项卡。
注意:如果选择未打开工作空间文件夹的解释器,则将
python.pythonPath
在您的用户设置中设置VS Code ,这通常设置VS Code的默认解释器。用户设置可确保您始终具有用于Python项目的默认解释器。通过工作区设置,您可以覆盖用户设置。
在“文件资源管理器”工具栏中,选择文件hello
夹上的“ 新建文件”按钮:
命名文件hello.py
,它将在编辑器中自动打开:
通过使用.py
文件扩展名,您告诉VS Code将这个文件解释为Python程序,以便它使用Python扩展名和选定的解释器评估内容。
注意:“文件资源管理器”工具栏还允许您在工作区中创建文件夹,以更好地组织代码。您可以使用“ 新建文件夹”按钮快速创建文件夹。
现在您的工作区中已有一个代码文件,在中输入以下源代码hello.py
:
msg = "Hello World"print(msg)
当您开始键入时print
,请注意IntelliSense如何显示自动完成选项。
IntelliSense和自动完成功能适用于标准Python模块以及您已安装到所选Python解释器环境中的其他软件包。它还提供了对象类型上可用方法的完成。例如,由于msg
变量包含字符串,因此在键入时IntelliSense提供了字符串方法msg.
:
可以尝试使用IntelliSense进行更多尝试,但是请还原所做的更改,以便仅包含msg
变量和print
调用,并保存文件(Ctrl + S)。
有关编辑,格式化和重构的完整详细信息,请参阅《编辑代码》。Python扩展还完全支持Linting。
It's simple to run hello.py
with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.
The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py
(macOS/Linux) or python hello.py
(Windows):
There are three other ways you can run Python code within VS Code:
Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):
Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.
From the Command Palette (Ctrl+Shift+P), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.
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's left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.
Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.
Note: VS Code uses JSON files for all of its various configurations; launch.json
is the standard name for a file containing debugging configurations.
These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.
The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg
variable appears in the Local pane.
A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (Shift+F11), restart (Ctrl+Shift+F5), and stop (Shift+F5).
The Status Bar also changes color (orange in many themes) to indicate that you're in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.
To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.
Tip Debugging information can also be seen by hovering over code, such as variables. In the case of
msg
, hovering over the variable will display the stringHello world
in a box above the variable.
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:
msgmsg.capitalize()msg.split()
Select the blue Continue button on the toolbar again (or press F5) 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.
If you restart the debugger, the debugger again stops on the first breakpoint.
To stop running a program before it's complete, use the red square stop button on the debug toolbar (Shift+F5), or use the Run > Stop debugging menu command.
For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.
Tip: Use Logpoints instead of print statements: Developers often litter source code with
Let's now run an example that's a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib
and numpy
packages to create a graphical plot as is commonly done with data science. (Note that matplotlib
cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)
Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py
, and paste in the following source code:
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the rangeplt.plot(x, np.sin(x)) # Plot the sine of each x pointplt.show() # Display the plot
Tip: If you enter the above code by hand, you may find that auto-completions change the names after the
as
keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.
Next, try running the file in the debugger using the "Python: Current file" configuration as described in the last section.
Unless you're using an Anaconda distribution or have previously installed the matplotlib
package, you should see the message, "ModuleNotFoundError: No module named 'matplotlib'". Such a message indicates that the required package isn't available in your system.
To install the matplotlib
package (which also installs numpy
as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Integrated Terminal (Ctrl+Shift+`). This command opens a command prompt for your selected interpreter.
A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment
that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:
Note: For additional information about virtual environments, see Environments.
Create and activate the virtual environment
Note: When you create a new virtual environment, you should be prompted by VS Code to set it as the default for your workspace folder. If selected, the environment will automatically be activated when you open a new terminal.
For windows
py -3 -m venv .venv.venv\scripts\activate
If the activate command generates the message "Activate.ps1 is not digitally signed. You cannot run this script on thecurrent system.", then you need to temporarily change the PowerShell execution policy to allow scripts torun (see About Execution Policies in the PowerShell documentation):
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
For macOS/Linux
python3 -m venv .venvsource .venv/bin/activate
Select your new environment by using the Python: Select Interpreter command from the Command Palette.
Install the packages
# Don't use with Anaconda distributions because they include matplotlib already.# macOSpython3 -m pip install matplotlib# Windows (may require elevation)python -m pip install matplotlib# Linux (Debian)apt-get install python3-tkpython3 -m pip install matplotlib
Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:
Once you are finished, type deactivate
in the terminal window to deactivate the virtual environment.
For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.
You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.
To learn more about the Python language, follow any of the programming tutorials listed on python.org within the context of VS Code.
To learn to build web apps with the Django and Flask frameworks, see the following tutorials:
There is then much more to explore with Python in Visual Studio Code:
联系客服