打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
<font style="vertical-align: inherit;"><font style="vertical-align: inherit;

VS Code中的Python入门

在本教程中,您将使用Python 3在Visual Studio Code中创建最简单的Python“ Hello World”应用程序。通过使用Python扩展,您可以将VS Code变成一个功能强大的轻量级Python IDE(您可能会找到PyCharm的高效替代品)。

本教程向您介绍VS Code作为Python环境,主要介绍如何通过以下任务来编辑,运行和调试代码:

  • 编写,运行和调试Python“ Hello World”应用程序
  • 了解如何通过创建Python虚拟环境来安装软件包
  • 编写一个简单的Python脚本以在VS Code中绘制图形

本教程无意教您Python本身。熟悉VS Code的基础知识之后,您可以在VS Code的上下文中遵循python.org上的任何编程教程,以对该语言进行介绍。

如果您有任何问题,请随时在VS Code文档库中提交本教程的问题

注意:在本教程中,您可以将VS Code与Python 2结合使用,但是需要对代码进行适当的更改,此处不做介绍。

先决条件

要成功完成本教程,您需要首先设置Python开发环境。具体来说,本教程要求:

  • VS代码
  • VS Code Python扩展
  • Python 3

安装Visual Studio代码和Python扩展

  1. 如果尚未这样做,请安装VS Code

  2. 接下来,从Visual Studio Marketplace 安装VS CodePython扩展有关安装扩展的更多详细信息,请参阅Extension MarketplacePython扩展名为Python,由Microsoft发布。

安装Python解释器

与Python扩展一起,您需要安装Python解释器。您使用哪种口译员取决于您的特定需求,但是下面提供了一些指导。

Windows

从python.org安装Python通常,您可以使用页面第一个出现Download Python按钮下载最新版本。

注意:如果您没有管理员权限,则在Windows上安装Python的另一个选择是使用Microsoft Store。Microsoft Store提供了Python 3.7Python 3.8的安装请注意,使用此方法可能与某些软件包存在兼容性问题。

有关在Windows上使用Python的其他信息,请参阅Python.org上的在Windows上使用Python。

macOS

不支持在macOS上系统安装Python。相反,建议通过Homebrew安装要在macOS上使用Homebrew安装Python brew install python3,请在终端提示下使用。

注意在macOS上,请确保PATH环境变量中包含VS Code安装的位置。有关更多信息,请参见这些设置说明

Linux

在Linux上的内置Python 3安装效果很好,但是要安装其他Python软件包,必须pip使用get-pip.py进行安装

其他选项

  • 数据科学:如果使用Python的主要目的是数据科学,那么您可以考虑从Anaconda下载Anaconda不仅提供Python解释器,而且还提供许多有用的数据科学库和工具。

  • 适用于Linux的Windows子系统:如果您正在Windows上工作,并且希望Linux环境可以与Python一起使用,那么可以选择适用于LinuxWindows子系统(WSL)。如果选择此选项,则还需要安装Remote-WSL扩展有关将WSL与VS Code一起使用的更多信息,请参见VS Code远程开发或尝试“ 在WSL中使用”教程,该教程将引导您完成设置WSL,安装Python以及创建在WSL中运行的Hello World应用程序。

验证Python安装

要验证您是否已在计算机上成功安装Python,请运行以下命令之一(取决于您的操作系统):

  • Linux / macOS:打开“终端窗口”并键入以下命令:

    python3 --version
  • Windows:打开命令提示符并运行以下命令:

    py -3 --version

如果安装成功,则输出窗口应显示您安装的Python版本。

注意可以py -0在VS Code集成终端中使用该命令来查看计算机上安装的python版本。默认解释器由星号(*)标识。

启动VS代码在一个项目(工作区)文件夹

使用命令提示符或终端,创建一个名为“ hello”的空文件夹,导航至该文件夹,然后通过输入以下命令code在该文件夹(.)中打开VS Code(

mkdir hellocd hellocode .

注意:如果您使用的是Anaconda发行版,请确保使用Anaconda命令提示符。

通过在文件夹中启动VS Code,该文件夹将成为您的“工作区”。VS Code将特定于该工作空间的.vscode/settings.json设置存储在中,这些设置与全局存储的用户设置分开。

或者,您可以通过操作系统UI运行VS Code,然后使用“ 文件”>“打开文件夹”打开项目文件夹。

选择Python解释器

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项目的默认解释器。通过工作区设置,您可以覆盖用户设置。

创建Python的Hello World的源代码文件

在“文件资源管理器”工具栏中,选择文件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

运行Hello World

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.

Configure and 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'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 string Hello 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 print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn't stop the program. For more information, see Logpoints in the main VS Code debugging article.

Install and use packages#

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.

  1. 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
  2. Select your new environment by using the Python: Select Interpreter command from the Command Palette.

  3. 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
  4. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

  5. 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.

Next steps#

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:

该文档对您有帮助吗?


2019/07/18
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
手把手将Visual Studio Code变成Python开发神器
Visual Studio Code 中的 Python 入门
windows上python开发环境的搭建
如何在Windows上使用Python进行开发(入门指南)
Python编辑器安装&使用教程
Windows下有哪些比较好用的Python IDE?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服