如何在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

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法