如何在Visual Studio Code中调试Python脚本-程序员宅基地

技术标签: python  java  linux  编程语言  人工智能  

In this article, I am going to explain how we can easily debug Python scripts using the Visual Studio (VS) Code. In my previous article on this topic, I have explained how to set up a development environment to start coding in Python. I would definitely recommend reading that article if you have not setup your Visual Studio Code environment yet. This article can be considered as a continuation from the above-mentioned steps as I am assuming that you are already into programming in Python using the VS Code.

在本文中,我将解释如何使用Visual Studio(VS)代码轻松调试Python脚本。 在上一篇关于该主题的文章中,我解释了如何设置开发环境以开始使用Python进行编码 。 如果您尚未设置Visual Studio Code环境,我绝对建议您阅读该文章。 可以将本文视为上述步骤的续篇,因为我假设您已经开始使用VS Code在Python中进行编程。

需要调试代码 (The need for debugging code)

While we talk about how to debug Python scripts in VS code, it is essential for us to know why we should debug our code in the first place. Not only for Python, debugging is related to every other programming language in the world, starting from C, C++, JavaScript, and so on. In the software programming world, debugging is the process that allows the programmer to identify and locate bugs/errors in the existing code. Debugging is an integral part of any software development life cycle and sometimes it can take more time to debug code than to write the same.

当我们谈论如何在VS代码中调试Python脚本时,对我们来说至关重要的是要知道为什么首先应该调试我们的代码。 不仅对于Python,调试还与世界上所有其他编程语言都息息相关,从C,C ++,JavaScript等开始。 在软件编程世界中,调试是使程序员能够识别和定位现有代码中的错误/错误的过程。 调试是任何软件开发生命周期不可或缺的一部分,有时调试代码要比编写代码花费更多的时间。

调试与测试相同吗? (Is debugging the same as testing?)

Not really, debugging and testing are two different terms and should not be confused with one another. Let me clear this out. Suppose you are developing a new project and you have written all your code and as per the business the requirements the code works well. Now, once you are done with the development, this code will be assigned to the QA engineer whose job is to test the application that you just developed. Let us assume that although the application works fine functionally, there is some issue due to which a calculation is being wrongly displayed. The QA engineer will then identify this as a defect/bug in your code and assign it back to you so that you can fix it.

并非如此,调试和测试是两个不同的术语,不应相互混淆。 让我清除这一点。 假设您正在开发一个新项目,并且您已经编写了所有代码,并且根据业务需求,该代码运行良好。 现在,一旦完成开发,此代码将分配给QA工程师,其工作是测试刚刚开发的应用程序。 让我们假设尽管该应用程序在功能上运行良好,但是由于某些问题导致计算显示错误。 然后,质量检查工程师将其识别为代码中的缺陷/错误,并将其分配给您,以便您进行修复。

Now, when you reproduce the code on your machine, your job is to identify the piece of code which is responsible for those calculations and identify the glitch in there. This process of identifying the correct code and trying to fix it with or finding another workaround is known as debugging. Although Visual Studio Code is capable of debugging most of the programming languages, we will use Python in this tutorial.

现在,当您在计算机上重现代码时,您的工作是确定负责这些计算的代码段,并确定其中的故障。 识别正确的代码并尝试使用正确的代码进行修复或寻找其他解决方法的过程称为调试。 尽管Visual Studio Code能够调试大多数编程语言,但在本教程中我们将使用Python。

在VS Code中调试Python脚本 (Debug Python scripts in VS Code)

Assuming that you have already set up your Python development environment, let us now understand how to debug Python scripts from VS Code directly. I will begin by writing some sample code which can be used for demonstration purposes. Please note that we will only focus on the debugging and writing the Python script is out of scope for this article.

假设您已经设置了Python开发环境,现在让我们了解如何直接从VS Code调试Python脚本。 我将首先编写一些示例代码,这些示例代码可用于演示。 请注意,我们将只专注于调试,而编写Python脚本超出了本文的范围。

Head over to the Visual Studio Code and create a new Python file. You can also use an existing file if you already have one. I am using the following code for demonstration purposes.

转到Visual Studio Code并创建一个新的Python文件。 如果已有文件,也可以使用现有文件。 我将以下代码用于演示目的。

# Debugging simple variable statements.
number = 100
print(f'Number is {number}')
  
number = 500
print(f'New Number is {number}')
  
# Debugging a for loop
userList = ['Rob','Dave','Fred']
  
for user in userList:
    print(user)

As you might be aware, you can just run this code by simply selecting Run Python File in Terminal from the context menu or by clicking on the Run icon on the top right corner. The following will be the result after the script is successfully executed.

您可能已经知道,只需在上下文菜单中选择“在Terminal中运行Python文件”,或单击右上角的“运行”图标 ,即可运行此代码。 以下是成功执行脚本后的结果。

Debug Python scripts in VS Code

Figure 1 – Executing Python Code in the Terminal

图1 –在终端中执行Python代码

Now that we know our code is executed, we can go ahead and run the debugger to test the code and the execution flow as well. You can start the debugger in the following ways.

现在我们知道我们的代码已执行,我们可以继续运行调试器以测试代码和执行流程。 您可以通过以下方式启动调试器。

  • Start Debugging from the 运行菜单中选择Run menu 开始调试
  • Run icon from the left pane and click on 运行”图标 ,然后单击“ Run and Debug 运行并调试”
  • F5 on the keyboard F5

I would like to go with the second option and hit Run and Debug.

我想选择第二个选项,然后单击“运行并调试”

Debug Python Scripts in VS Code

Figure 2 – Debug Python Scripts in VS Code

图2 –在VS代码中调试Python脚本

As soon as you hit the Run and Debug button, a popup will appear in VS Code which will prompt you to choose the Debug Configuration that you would like to use. Let us go ahead with the Python File option for the time being. You can select other debug configurations based on the application that you are working with.

按下“ 运行并调试”按钮后,VS Code中将出现一个弹出窗口,提示您选择要使用的调试配置 。 现在让我们继续使用Python File选项。 您可以根据正在使用的应用程序选择其他调试配置。

Selecting Debug Configuration in VS Code

Figure 3 – Selecting Debug Configuration in the VS Code

图3 –在VS代码中选择调试配置

As you select the debug configuration in Visual Studio Code, you can see that the Terminal window opens up from the bottom and the debugger starts executing your code.

在Visual Studio Code中选择调试配置时,可以看到“终端”窗口从底部打开,调试器开始执行代码。

Debug Python scripts

Figure 4 – Debugger started

图4 –调试器已启动

Let me quickly explain the various areas that you can see on the screen.

让我快速解释一下您可以在屏幕上看到的各个区域。

Debug Toolbar – This is the main toolbar that allows you to navigate along with your code as you try to debug it. There are six actions on this toolbar which are as follows:

调试工具栏 –这是主要工具栏,可让您在尝试调试代码时随代码一起导航。 此工具栏上有六个操作,如下所示:

Debug Toolbar

Figure 5 – Debug Toolbar

图5 –调试工具栏

  • Continue/Pause (F5) – Allows you to pause or continue the debugging process

    继续/暂停(F5)–允许您暂停或继续调试过程
  • Step Over (F10) – Allows you to move over to the next line of code

    单步执行(F10)–允许您移至下一行代码
  • Step Into (F11) – Allows you to enter inside a different method during debugging

    单步执行(F11)–允许您在调试期间输入其他方法
  • Step Out (Shift+F11) – Allows you to move to the parent stack

    移出(Shift + F11)–允许您移至父堆栈
  • Restart (Ctrl+Shift+F5) – Restarts the debugging session from the beginning

    重新启动(Ctrl + Shift + F5)–从头开始重新启动调试会话
  • Stop (Shift+F5) – Stops the debugging session

    停止(Shift + F5)–停止调试会话

Variables Pane – Using the variables pane you can easily inspect the data elements within your program. When you start debugging a lot of system-defined variables are initiated along with the user-defined variables. During the debugging session, you can verify the values of each of those variables from this pane.

变量窗格 –使用变量窗格,您可以轻松检查程序中的数据元素。 开始调试时,会同时启动许多系统定义的变量和用户定义的变量。 在调试会话期间,您可以从此窗格验证每个变量的值。

Debug Python Scripts

Figure 6 – Variables Pane in the VS Code

图6 – VS代码中的变量窗格

Watch Pane – Sometimes you may write a program with hundreds of variables within it. It is not possible to monitor the values of all those variables from the Variables pane as mentioned above. In such a case, you might want to monitor only one or two variables of your choice leaving the worry about the rest. You can add those variables to your watch list, and you can easily monitor the status and the values for those particular variables within this pane.

看板 –有时您可能会编写一个包含数百个变量的程序。 如上所述,无法从“变量”窗格监视所有这些变量的值。 在这种情况下,您可能只想监视您选择的一个或两个变量,而不必担心其余的变量。 您可以将这些变量添加到监视列表中,并且可以在此窗格中轻松监视这些特定变量的状态和值。

Watch Pane in VS Code

Figure 7 – Watch Pane in VS Code

图7 – VS代码中的监视窗格

Call Stack Pane – This is helpful when your code has a lot of inner methods and you navigate deep inside a stack and then you might lose track of your stack. When there is any error in your program you can easily know from which stack is the error has occurred and then debug it accordingly.

调用堆栈窗格 –当您的代码具有很多内部方法并且在堆栈内部进行深入导航时可能会有所帮助,这很有用。 当程序中有任何错误时,您可以轻松地从哪个堆栈中发现错误发生了,然后进行相应的调试。

Breakpoints – This is an important concept while debugging code in any language. You may notice that while you initially started the debugger session, the terminal just executed the script and the debugging session stopped automatically. What if you want to stop the debugging session at some particular line and monitor the variables closely? In such a case, the breakpoints come to our rescue. You can attach a breakpoint to any line by just click on the left of the line number. A red dot will appear which means that the breakpoint has been defined for that line. The next time when you debug, you can see that the program stops the execution at the line and waits for your command. You can now use the Debug Toolbar to navigate along with your code.

断点–这是调试任何语言的代码时的重要概念。 您可能会注意到,在最初启动调试器会话时,终端仅执行了脚本,调试会话自动停止。 如果要在某些特定的行上停止调试会话并密切监视变量怎么办? 在这种情况下,断点就可以解决。 只需单击行号左侧,即可将断点附加到任何行。 将出现一个红点,表示已为该行定义了断点。 下次调试时,您会看到程序在该行停止执行并等待命令。 现在,您可以使用“调试工具栏”与代码一起导航。

Debug Python Scripts using breakpoint

Figure 8 – Breakpoints in VS Code

图8 – VS代码中的断点

结论 (Conclusion)

In this article, we have talked about the various topics on how to debug Python scripts in Visual Studio Code. As already discussed, Visual Studio Code is by far one of the simplest, yet powerful tools from Microsoft and used by many developers for the development of their applications. While writing complex applications, it often becomes a pain point to identify bugs in the existing system. In order to understand the complete flow and remove those bugs, debugging helps us to identify those pain points and understand them with more details about the execution flow of the application. Debugging should be considered as one of the core parts of any application development.

在本文中,我们讨论了有关如何在Visual Studio Code中调试Python脚本的各种主题。 正如已经讨论过的,Visual Studio Code到目前为止是Microsoft提供的最简单但功能强大的工具之一,许多开发人员都在使用Visual Studio Code来开发其应用程序。 在编写复杂的应用程序时,识别现有系统中的错误通常会很痛苦。 为了了解完整的流程并消除这些错误,调试可以帮助我们识别这些痛点,并通过有关应用程序执行流程的更多详细信息来理解它们。 调试应被视为任何应用程序开发的核心部分之一。

翻译自: https://www.sqlshack.com/how-to-debug-python-scripts-in-visual-studio-code/

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/culuo4781/article/details/107625820

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签