VS Code python使用笔记之toturial

VS Code python 使用笔记之 toturial

前言

我其实使用 VS Code 学习 python 已经有一段时间,但是对于 python 的配置仍然很不清晰,用的云里雾里。所以痛定思痛决定学一波官方文档,相信能事倍功半。于是我就将文档初略的翻译一遍。由于英语水平实在有限,肯定有不少错误,欢迎指正。如果看了本文仍然有疑惑,那请看官方文档

该文档是根据 VS Code 1.27 版本翻译的

Getting Started with Python in VS Code(在 VS Code 中使用 python)

In this tutorial you use Python 3 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 (which you may find a productive alternative to PyCharm).

在本教程中你将使用 python3 在 Visual Studio Code 去创建最简单的应用“Hello,World”。通过使用 Python 拓展,你能使 VS Code 变成一个轻量的 python IDE(你可能会把它当成 Pycharm 的很好替代品)

Note: You can use VS Code with Python 2 with this tutorial, but you need to make appropriate changes to the code.

注意:这个教程中你也能使用 VS Code 编辑 python2 ,但是你需要在代码中做一些恰当的修改。

Prerequisites(预先准备)

发先这一章没什么重点内容我就不翻译了,直接摘录过来。

To successfully complete this tutorial, you must do the following:

  1. Install the Python extension for VS Code.

  2. Install a version of Python 3 (for which this tutorial is written). Options include:

    • (All operating systems) A download from python.org; typically use the Download Python 3.6.5 button that appears first on the page (or whatever is the latest version).
    • (Linux) The built-in Python 3 installation works well, but to install other Python packages you must run sudo apt install python3-pip in the terminal.
    • (MacOS) An installation through Homebrew on macOS using brew install python3 (the system install of Python on macOS is not supported).
    • (All operating systems) A download from Anaconda (for data science purposes).
  3. On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check this by running path at the command prompt. If the Python interpreter’s folder isn’t included, open Windows Settings, search for “environment”, select Edit environment variables for your account, then edit the Path variable to include that folder.

Start VS Code in a project (workspace) folder(启动 VS Code 在一个工程(工作空间)文件夹)

At a command prompt or terminal, create an empty folder called “hello”, navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

在命令提示行或者终端中,创建一个叫“hello”的空文件夹,切换进去.通过键入下面的命令,使用(code)打开 VS Code 在文件夹(.)中:

mkdir hello
cd hello
code .

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.

通过一个文件夹启动 VS Code 这个文件夹会变成你的工作空间,VS Code 存储特定工作空间的设置在 .vscode/settings.json 中,它与其他的用户设置分离并且是全局性的。

Select a Python interpreter(选择一个 python 解释器)

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.

Python 是一门解释型的语言,为了运行 python 代码和使用智能感知功能,你必须告诉 VS Code 使用哪个解释器。

From within VS Code, select a Python 3 interpreter by opening the Command Palette (kb(workbench.action.showCommands)), 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):

在 VS Code 通过打开 命令面板 (kb(workbench.action.showCommands)),选择一个 python3 的解释器(我插一句他这上面的命令我也没看懂,不过命令面板可以通过 ctrl+shift+p 打开。)。开始输入 Python: Select Interpreter 命令进行搜索,然后选择这个命令。你也能使用状态栏中的 Select Python Environment 选项,如果可用的话(它可能也显示被选择的解释器)。

no-interpreter-selected-statusbar

The command presents a list of available interpreters that VS Code can find automatically. If you don’t see the desired interpreter, see Configuring Python environments.

这个命令列出了 VS Code 自动搜索的一系列可用的解释器。如果你没有看到想要的解释器,请看Configuring Python environments.(这边说一句,这些文档之类的链接我就不提供了,需要看的话自己从官网看)

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 (Code > Preferences > Settings on macOS), then select the Workspace Settings tab.

选择解释器通过设置 python.pythonPath 值在你的工作空间的设置文件中。想要看到设置,选择 文件 > 首选项 > 设置 > (代码 > 首选项 > 设置 在 macOS),然后选择 工作空间设置 标签。

Note: If you select an interpreter without a workspace folder open, VS Code sets python.pythonPath in your user settings instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

注意: 如果你选择一个解释器并且没打开工作空间文件夹,VS Code 会使用用户设置中的 python.pythonPath 做为替代,它也正是 VS Code 的全局默认解释器。用户设置会确保你总是有个默认的解释器用于 Python 工程。而工作空间的设置则会覆盖用户设置。

Create a Python Hello World source code file(创建一个 Python Hello World 源代码文件)

From the File Explorer toolbar, press the New File button on the hello folder:

在文件资源管理器的工具栏中,hello 文件夹上点击新建文件按钮:

toolbar-new-file

Name the file hello.py, and it automatically opens in the editor:

命名文件为 hello.py,然后它会自动在编辑器中打开。

hello-py-file-created

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.

通过 .py 文件拓展名,VS Code 解释这个文件作为 Python 文件并且评估内容通过 Python 拓展应用和被选择的解释器。

Next, start entering the following source code if using Python 3:

现在,开始输入下面的源代码如果你使用 Python3

msg = "Hello World"
print(msg)

When you start typing print, notice how IntelliSense presents auto-completion options.

当你开始输入 print ,注意 智能感知 如何展现自动补全选项。

intellisense01

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(智能感知)和 auto-completions(自动补全)既工作于 Python 标准组件也工作于其他你已经安装在当前解释器环境下的包。它也提供方法的补全功能在对象类型的方法中。例如,因为 msg 变量包含一个字符串,智能感知提供字符串方法补全在你输入 msg的时候。

intellisense02

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 (kb(workbench.action.files.save)).

可以随意尝试智能感知功能,但随后还原这些改变以便于你仅有 msg 变量和 print 调用,然后保存这个文件。

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

关于编辑、格式和重构,全部的细节见 Editing code。Python 拓展也有全部的 Linting 支持。

Run Hello World(运行 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):

很容易去运行 hello.py。在编辑器中单击右键,选择 Run Python File in Terminal(它会自动保存文件):

run-python-file-in-terminal

The command opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

这个命令打开一个终端面板,在终端面板你的 Python 解释器被自动激活。然后运行 python3 hello.py(macOS/Linux)or python hello.py(Windows):

output-in-terminal

There are two other ways you can run Python within VS Code:

这是两种其他方式你能运行 Python 使用 VS Code:

  • Select one or more lines, then press kbstyle(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.
  • 选择一行或多行,然后按 shift+enter键或者右键单击然后选择 Run Selection/Line in Python Terminal 这个命令能非常方便地测试一部分文件。
  • Use the Python: Start REPL command to opens 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.
  • 使用 Python: Start REPL 命令去打开一个 REPL 终端在当前选择的 Python 解释器。在 REPL 中,你能一次性输入运行几行代码。

Configure and run the debugger(配置和运行调试)

Let’s now try debugging our simple Hello World program.

现在尝试调试我们简单的例子 Hello World 程序。

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing kb(editor.debug.action.toggleBreakpoint). Alternately, just click in the editor left gutter next to the line numbers. A red circle appears in the gutter.

首先,通过把鼠标放在 print 行,通过命令面板输入断点选择命令,设置一个断点在 hello.py 的第二行。或者,仅通过单击编辑器左边靠近行数的边槽。一个红色的断点出现在边槽中。

breakpoint-set

Next, select the Debug View in the sidebar:

下一步,选择调试界面在侧边栏中:

debug-icon

Then select the settings icon on the debug toolbar (or use the Debug > Open configurations menu command):

然后选择设置图标在调试工具栏(或者使用 调试 > 打开配置 菜单命令)

debug-settings

The command opens a menu of available debuggers, which shows Python and Python Experimental. Select Python. The Python extension then creates a launch.json file that contains a number of configurations, which appear in the configurations drop-down:

这个命令打开可以调试器的菜单,它显示 PythonPython Experimental。 选择 Python。Python 拓展会创建一个 launch.json 文件包含许多配置,它会出现在你下拉配置的时候。

debug-configurations

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

注意:VS Code 使用 JSON 文件配置各种设置。launch.json 是包含了调试配置文件的标准名。

These different configurations are fully explained in Debugging configurations; for now, just select “Python: Current File”, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

这些不同的配置都有在 Debugging configurations 中做解释。现在选择 “Python: Current File”,它是使用当前被选择的 Python 解释器运行当前编辑器中的文件的配置。

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:

为了当程序运行时自动停止调试在第一行,添加 "stopOnEntry": true 设置到“Python: Current File”配置对应的 launch.json,使得整个配置如下:

{
    "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 kb(workbench.action.debug.start). Because stopOnEntry 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:

保存 launch.json,返回编辑器中的 hello.py,然后通过选择调试工具条上的绿箭头或者按下 kb(workbench.action.debug.start) 运行调试。因为 stopOnEntry 被设置为真,这个调试器停止在文件的第一行。当前行由左边缘的黄色箭头标明。如果此时你看本地变量窗口,你会看到自动创建的 dunder variables。

debug-step-01

A debug toolbar appears along the top with the following commands from left to right: run (kb(workbench.action.debug.start)), step over (kb(workbench.action.debug.stepOver)), step into (kb(workbench.action.debug.stepInto)), step out (kb(workbench.action.debug.stepOut)), restart (kb(workbench.action.debug.restart)), and stop (kb(workbench.action.debug.stop)).

一个调试工具条会出现在页面顶端,从左到右一次有如下命令:运行 (kb(workbench.action.debug.start)), 单步执行 (kb(workbench.action.debug.stepOver)), 步入 (kb(workbench.action.debug.stepInto)), 步出 (kb(workbench.action.debug.stepOut)), 重新开始 (kb(workbench.action.debug.restart)), 停止 (kb(workbench.action.debug.stop)).

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.

状态栏也会变色(许多主题中是橘黄色)表明调试的模式。Python 调试控制台 也会自动出现在右下方的面板中用于显示单独运行的的命令和程序输出。

To continue running the program, select the run command on the debug toolbar (kb(workbench.action.debug.start)) 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

为继续运行程序,选择调试工具条中的运行命令 (kb(workbench.action.debug.start)) 或者调试视图中的绿色箭头。调试器运行程序到下一个断点。现在定义的 msg 变量出现在本地变量面板中。

debug-step-02

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:

你也能够操作变量在 调试控制台 (如果你没有看见,在 VS Code 的右下方区域选择 调试控制台 ,或者从 菜单中选择)。然后在控制台的方框中的命令提示符 > 后,试着一步一步输入下面的几行命令:

msg
msg.capitalize()
msg.split()

debug-step-03

Select the green arrow 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.

选择再次绿色箭头完成运行 “Hello World”出现在 Python 调试控制台 如果你切换回去,VS Code 曾经存在的调试模式已经完成。

If you restart the debugger, remember that you set stopOnEntry in the configuration so that the debugger stops before running any code. To run all the way to the first breakpoint, remove that entry from the configuration.

如果你重启调试器,记得设置配置中的 stopOnEntry 选项使得调试停止在运行代码之前。为了能一直运行到第一个断点,可以移除这个设置。

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (kb(workbench.action.debug.stop)), or use the Debug > Stop debugging menu command.

可以使用调试工具栏中红色方框按钮(kb(workbench.action.debug.stop)),或者使用 调试 > 停止调试 菜单命令,停止在程序完成前停止运行。

For full details, see Debugging configurations, which includes details on how to use a use a specific Python interpreter for debugging.

至于更多细节请看 Debugging configurations,该文档包括了很多关于如何去使用特定的 Python 解释器去调试。

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 if you choose the Python Experimental debugger. 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.

建议:Logpoints 替代打印语句:开发者们经常乱用带有 print 的源代码去迅速了解变量而不是在调试器中让每一行代码经过必要的停顿。在 VS Code 中,你能使用 Logpoints 功能,如果你选择了 Python Experimental 调试器。Logpoint 就像断点但是它记录信息到控制台却不中断程序运行。想要了解更多信息,请看 Logpoints 在 VS Code 主要的调试文章。

Troubleshooting(故障排查)

If for some reason VS Code doesn’t generate launch.json for you, create a file by that name within the folder named .vscode folder (creating it if you need to), then paste the following contents into launch.json:

如果一些原因使得 VS Code 不能生成 launch.json 文件,你能使用这个文件名创建一个文件在名为 .vscode 的文件夹下(创建这个文件夹如果你需要的话),然后复制下面的内容到 launch.json 文件中。

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}"
        }
    ]
}

If you see “SyntaxError: invalid syntax” as shown below, you attempted to start to debugger when launch.json is currently showing in the editor, which is not Python code like hello.py:

如果你看到下面显示 “语法错误:无效语法” ,你尝试启动调试,当 launch.jsoh 如当前的编辑器中时,这意味着现在不是和 hello.py 一样的 Python 代码。

    // Use IntelliSense to learn about possible attributes.
     ^
SyntaxError: invalid syntax

Select hello.py and try again. Alternately, create a debug configuration specifically for the hello.py file by adding the following lines in launch.json within the configuration array. Then select this configuration in the debugger drop-down and start the debugger again.

选择 hello.py 然后再次尝试。依下次序,先通过添加下面这些行到 launch.json 文件中,创建一个特定的调试配置给在配置组中的 hello.py 文件。然后下拉选择调试器中的配置,再次启动调试。

        {
            "name": "Python: hello.py",
            "type": "python",
            "request": "launch",
            "program": "hello.py"
        },

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 commonly done with data science.

现在让我们运行一个更有趣的例子。在 Python 中,包是你获得的许多有用的代码库,一般从 PyPi。在这个例子中,你将使用 matplotlib 和 numpy 包去绘图就像数据科学里经常做的一样。

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:

返回到 资源管理器 视图(左边栏最顶端的图标),创建一个名为 standardplot.py 的新文件,粘贴上下面的源代码:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.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.

建议:如果你手动输入上面的代码,你可能会发现当你在行末尾按 Enter 键的时候,自动补全会改变as 关键字的名字。为了避免这种情况,输入一个空格再输入 Enter。

Next, try running the file in the debugger using the “Python: Current file” configuration as described in the last section. (If you still have "stopOnEntry": true in that configuration, you need to select the run command again to continue.)

下一步,尝试在调试器中使用在上一节的 “Python:Current file” 配置,运行这个文件。(如果你配置中还有 "stopOnEntry": true 这一项的话,你需要再次选择运行命令继续运行。)

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.

除非你在使用 Anaconda 发行版或者之前安装了 matplotlib 包,否则你会看到信息 “ModuleNotFoundError: No module named ‘matplotlib”。这个信息意味着在你的系统中所需要的包是不可用的。

To install the matplotlib package (which also installs numpy), stop the debugger and run Python: Create Terminal from the Command Palette, which opens a command prompt for your selected interpreter. Then enter the following commands as appropriate for your operating system (commands may require elevation if the Python interpreter is installed in a protected area of the file system):

为了安装 matplotlib 包(也安装了 numpy),停止调试并且在命令面板中运行 Python: Create Terminal,这会为你选择的解释器打开一个命令提示行。然后根据对应的操作系统输入下面的命令(如果 Python 解释器被安装在受保护的系统区域,命令可能需要升级):

Note: If you are unable to install the package, please file an issue on GitHub so we can help you investigate.

注意:如果你无法安装该包,请 file an issue on GitHub,以便我们能帮助你调查。

# pip[3] install commands may require elevation

# macOS
pip3 install matplotlib

# Windows
pip install matplotlib

# Linux
sudo apt-get install python3-tk
pip3 install matplotlib

Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

现在运行这个程序(有或没有调试),一会儿之后会输出一个绘图窗口:

plot-outputmatplotlib output

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.

你能配置 VS Code 去使用任何你安装的 Python 环境,包括虚拟机和 conda。
你也能使用单独的环境去调试。更多的细节,请看 Environment

There is then much more to explore with Python in Visual Studio Code:

在VS Code 中使用 Python 有更多的东西需要探索(这下面就不翻译了):

  • Python environments - Control which Python interpreter is used for editing and debugging.
  • Editing code - Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting - Enable, configure, and apply a variety of Python linters.
  • Debugging - Learn to debug Python both locally and remotely.
  • Unit testing - Configure unit test environments and discover, run, and debug tests.
  • Settings reference - Explore the full range of Python-related settings in VS Code.

猜你喜欢

转载自blog.csdn.net/m0_37639589/article/details/82506271
今日推荐