一、先决条件
-
安装Python插件。
-
安装Python 3的一个版本,有几种途径:
- Linux上的内置Python安装。
- MacOS上使用brew安装。
brew install python3
- 从python.org下载。
- 从Anaconda下载(用于数据科学目的)。
二、创建一个文件夹和源代码文件
$ mkdir hello
$ cd hello
$ touch hello.py
使用VS Code 打开文件夹

在hello.py
中输入源码
msg = "Hello World"
print(msg)
当你开始输入时print
,注意IntelliSense如何呈现自动完成选项。

智能感知和自动补全适用于标准Python模块以及你安装到所选Python解释器环境中的其他软件包。它还为对象类型提供的方法提供完成。例如,因为该msg变量包含一个字符串,所以IntelliSense提供了字符串方法,然后键入msg.:

三、选择一个Python解释器
- 找到python3系统所在路径
$ type -a python3

-
编辑器设置
演示.png
演示.png
四、运行Hello World

该命令将打开一个终端面板,你的Python解释器会自动激活,然后运行python3 hello.py(Mac / Linux)或python hello.py:

五、配置并运行调试器
首先,单击编号旁边的编辑器左边的装订线会看到如下红点。

接下来,选择边栏中的调试视图:

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

该命令打开一个可用调试器的菜单,其中显示了Python和Python Experimental。选择Python。然后Python扩展会创建一个launch.json文件,其中包含许多配置,这些配置将显示在配置下拉列表中:

注意:VS Code使用JSON文件进行各种配置;
launch.json
是包含调试配置的文件的标准名称。调试中充分说明了这些不同的配置; 现在,只需选择“Python:Current File”,即使用当前选择的Python解释器运行编辑器中显示的当前文件的配置。
要使程序启动时在第一行自动停止等待调试,请将"stopOnEntry": true
设置添加到“Python:Current File”配置中launch.json
,如下所示:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"stopOnEntry": true
},
切换到hello.py编辑器,然后通过选择Debug工具栏中的绿色箭头或按F5来运行调试器。由于stopOnEntry设置为true,所以调试器停止在文件的第一行。当前行在左边空白处用黄色箭头表示。如果你在此处查看局部变量窗口,则会看到只定义了自动dunder变量:

选择调试工具栏上的绿色箭头以继续运行程序(F5),调试器在断点处停止。现在定义的msg变量出现在本地窗格中,你可以在调试控制台中使用变量(选择VS代码右下角的“DEBUG CONSOLE”):

六、故障排除#
如果由于某种原因,VS Code不能生成launch.json,请在名为.vscode的文件夹内创建一个文件launch.json并粘贴以下内容:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}"
}
]
}
如果你看到下面的错误,那是因为你开始调试时选择的文件是launch.json而不是hello.py:
// Use IntelliSense to learn about possible attributes.
^
SyntaxError: invalid syntax
选择hello.py并重试。或者,通过launch.json在configuration数组中创建hello.py配置,然后在调试器下拉列表中选择该配置并再次启动调试器。
{
"name": "Python: hello.py",
"type": "python",
"request": "launch",
"program": "hello.py"
},
七、安装和使用软件包#
现在让我们来看一个更有趣的例子。在Python中,包是指你获得的任意数量的有用的代码库,通常来自PyPi。在这个例子中,我们使用matplotlib和numpy包创建一个曲线图。
- 首先创建新文件standardplot.py,并粘贴以下源代码:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
x = np.linspace(0, 20, 100) # 创建在一定范围内间隔均匀数字列表
plt.plot(x, np.sin(x)) # 绘制每个x点的正弦值
plt.show() # 显示列表
绘制每个x点的正弦值
显示图
- 运行程序
未安装包的情况下报异常
ModuleNotFoundError: No module named 'matplotlib'
切换到终端执行pip3 install matplotlib

重新运行结果

谢谢~
网友评论